Skip to content

kunl/playwright_test

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🚀 Playwright PDF 生成器

一个基于GitHub Actions和Playwright的自动化PDF生成器,通过GitHub Issue自动将网页URL转换为PDF文件。

GitHub Actions Node.js Playwright

✨ 功能特点

  • 🔄 自动化流程: 创建GitHub Issue即可自动生成PDF
  • 🌐 网页转PDF: 使用Playwright将任何网页转换为高质量PDF
  • 📁 自动存储: PDF文件自动保存到仓库的pdf/目录
  • 💬 智能反馈: 自动在Issue中回复生成结果
  • 🔔 Webhook支持: 可配置外部Webhook接收通知
  • 🛡️ 错误处理: 完善的错误捕获和日志记录
  • 📊 模块化设计: 代码结构清晰,易于维护和扩展

🎯 使用场景

  • 📄 文档归档: 自动将在线文档转换为PDF备份
  • 📰 新闻保存: 保存感兴趣的新闻文章为PDF
  • 📚 内容收集: 批量收集网页内容为PDF合集
  • 🔄 静态转换: 将动态网页转换为可分享的PDF文件

备注: 如果有需要,可将生成的PDF上传到阿里云OSS或其他云存储服务上,以提供更稳定的访问链接和更好的性能。

🚀 快速开始

1. Fork 项目

git clone https://github.com/your-username/playwright_test.git
cd playwright_test

2. 启用 GitHub Actions

  1. 在仓库的 Settings > Actions 中启用Actions
  2. 确保有Workflow权限:
    Settings > Actions > General > Workflow permissions
    选择 "Read and write permissions"

3. 配置 Secrets(可选)

项目无需额外配置即可运行。如需启用Webhook通知,可在仓库的 Settings > Secrets and variables > Actions 中添加:

  • WEBHOOK_URL: 外部Webhook接收URL(用于通知第三方系统)

4. 创建 Issue 触发

在仓库中创建一个新的Issue:

标题: 生成PDF - https://example.com

内容可以是任何内容,只要包含要转换的URL即可。
系统会自动提取页面标题并生成PDF。

📖 使用说明

基本用法

  1. 创建 Issue: 在仓库中创建新的Issue
  2. 包含URL: 在Issue标题或正文中包含要转换的网页URL
  3. 等待处理: GitHub Actions会自动运行,生成PDF
  4. 查看结果:
    • PDF文件保存在 /pdf/ 目录
    • Issue中会收到自动回复,显示下载链接

URL 格式支持

  • https://example.com
  • http://example.com
  • example.com (自动添加 https://)
  • ✅ 带有查询参数的URL
  • ✅ 锚点链接

示例 Issue 标题

生成PDF - https://www.example.com
PDF转换 - docs.company.com/api-guide  
新闻归档 - https://news.site.com/article/123

⚙️ 配置选项

环境变量

项目运行时所需的上下文信息由GitHub Actions自动提供,无需手动配置。只有Webhook URL需要可选配置:

变量名 必需 描述 示例
WEBHOOK_URL 外部Webhook通知URL(可选) https://hooks.slack.com/...

说明: GITHUB_TOKENGITHUB_REPOSITORYISSUE_NUMBERISSUE_BODY 等信息由GitHub Actions运行时自动提供,无需额外配置。

PDF 生成配置

PDF生成参数在 scripts/generate-pdf.js 中配置:

await page.pdf({
  path: filePath,
  format: 'A4',                    // 页面格式
  margin: {                        // 页边距
    top: '20mm',
    right: '20mm', 
    bottom: '20mm',
    left: '20mm'
  },
  printBackground: true            // 包含背景色
});

🏗️ 项目结构

📁 项目根目录/
├── 📄 .github/workflows/generate-pdf.yml  # GitHub Actions工作流
├── 📁 scripts/                            # 核心功能模块
│   ├── 📄 handle-issue.mjs               # 主控制器
│   ├── 📄 generate-pdf.mjs               # PDF生成引擎
│   ├── 📄 git-operations.mjs             # Git仓库操作
│   ├── 📄 github-api.mjs                 # GitHub API接口
│   └── 📄 webhook.mjs                    # Webhook通知
├── 📁 pdf/                               # PDF输出目录
├── 📄 package.json                       # 项目依赖配置
└── 📄 README.md                          # 项目文档

🔧 开发指南

本地测试

# 1. 安装依赖
npm install

# 2. 安装Playwright浏览器
npx playwright install chromium

# 3. 设置环境变量
export GITHUB_TOKEN="your-token"
export GITHUB_REPOSITORY="owner/repo"

# 4. 测试运行
npm run handle-issue

自定义配置

修改PDF格式

scripts/generate-pdf.js 中调整PDF参数:

await page.pdf({
  format: 'Letter',        // A4, Letter, Legal等
  landscape: true,         // 横版模式
  printBackground: true,   // 包含背景
  preferCSSPageSize: true  // 使用CSS页面大小
});

添加新的URL验证规则

scripts/handle-issue.js 中扩展URL解析逻辑。

上传到S3示例

如果需要将PDF上传到AWS S3存储桶,可以参考以下代码示例:

const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const fs = require('fs');

// 配置S3客户端
const s3Client = new S3Client({
  region: process.env.AWS_REGION || 'us-east-1',
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  },
});

// 上传PDF到S3
async function uploadToS3(filePath, key) {
  try {
    const fileContent = fs.readFileSync(filePath);

    const uploadParams = {
      Bucket: process.env.S3_BUCKET_NAME,
      Key: key,
      Body: fileContent,
      ContentType: 'application/pdf',
      ACL: 'public-read', // 或根据需要设置权限
    };

    const command = new PutObjectCommand(uploadParams);
    const result = await s3Client.send(command);

    console.log('✅ PDF uploaded to S3 successfully');
    return `https://${process.env.S3_BUCKET_NAME}.s3.amazonaws.com/${key}`;
  } catch (error) {
    console.error('❌ S3 upload failed:', error.message);
    throw error;
  }
}

// 在handle-issue.js中集成示例
// 在生成PDF后添加:
// const s3Url = await uploadToS3(pdfResult.filePath, `pdf/issue-${issueNumber}.pdf`);

首先安装AWS SDK依赖:npm install @aws-sdk/client-s3

然后配置环境变量:AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION, S3_BUCKET_NAME

🐛 故障排查

常见问题

1. Playwright浏览器未安装

错误信息:

❌ Error generating PDF: browserType.launch: Executable doesn't exist

解决方案: 在workflow中添加浏览器安装步骤:

# 在 .github/workflows/generate-pdf.yml 中添加
- name: Install Playwright browsers
  run: npx playwright install chromium

2. 网页访问超时

错误信息:

❌ Error generating PDF: Navigation timeout of 30000 ms exceeded

解决方案: 增加超时时间或检查网页可访问性:

await page.goto(url, {
  waitUntil: 'domcontentloaded',  // 改为更宽松的加载条件
  timeout: 60000                   // 增加超时时间
});

3. 权限不足

错误信息:

❌ Git operation failed: Permission denied

解决方案: 检查GitHub Actions权限设置:

# 在 .github/workflows/generate-pdf.yml 中设置
permissions:
  contents: write  # 允许推送文件
  issues: write    # 允许评论

4. PDF生成失败

错误信息:

❌ Error generating PDF: Failed to load page

解决方案:

  1. 检查URL是否可公开访问
  2. 确认网页支持自动化访问
  3. 添加用户代理或其他请求头

调试模式

在workflow中启用详细日志:

- name: Generate PDF and process
  env:
    # ... 其他环境变量
    DEBUG: true
  run: npm run handle-issue

查看运行日志

  1. 进入GitHub仓库的Actions页面
  2. 点击失败的workflow运行
  3. 查看详细的执行日志
  4. 重点关注 generate-pdf 步骤的输出

🔒 安全考虑

  • ✅ 所有敏感信息通过GitHub Secrets管理
  • ✅ 使用官方Docker镜像,确保环境安全
  • ✅ 最小权限原则,只请求必要的权限
  • ✅ URL访问仅限于公开网页
  • ✅ 生成的文件存储在用户自己的仓库中

⚡ 工作流优化

为提升GitHub Actions性能和安全性,已实施以下优化:

性能优化

  • NPM缓存: 使用 actions/cache 缓存 node_modules,加速依赖安装
  • 并发控制: 新Issue触发时自动取消之前的运行,避免冲突
  • 超时设置: 作业超时10分钟,防止长时间挂起

版本管理

  • 精确版本: Actions使用具体版本号,确保可重现性
  • 依赖审计: 安装后运行 npm audit 检查安全漏洞

容器配置

  • Playwright容器: 使用 mcr.microsoft.com/playwright:v1.56.1-jammy,预装浏览器
  • Node.js版本: 指定Node.js 20,确保兼容性

Workflow Improvements (English)

To enhance GitHub Actions performance and security, the following optimizations have been implemented:

Performance Optimizations

  • NPM Caching: Use actions/cache to cache node_modules, speeding up dependency installation
  • Concurrency Control: Automatically cancel previous runs when new issues trigger workflow to avoid conflicts
  • Timeout Settings: Job timeout of 10 minutes to prevent hanging workflows

Version Management

  • Precise Versions: Actions use specific version numbers for reproducibility
  • Dependency Audit: Run npm audit after installation to check for security vulnerabilities

Container Configuration

  • Playwright Container: Use mcr.microsoft.com/playwright:v1.56.1-jammy with pre-installed browsers
  • Node.js Version: Specify Node.js 20 for compatibility

⚡ 工作流优化

为提升GitHub Actions性能和安全性,已实施以下优化:

性能优化

  • NPM缓存: 使用 actions/cache 缓存 node_modules,加速依赖安装
  • 并发控制: 新Issue触发时自动取消之前的运行,避免冲突
  • 超时设置: 作业超时10分钟,防止长时间挂起

版本管理

  • 精确版本: Actions使用具体版本号,确保可重现性
  • 依赖审计: 安装后运行 npm audit 检查安全漏洞

容器配置

  • Playwright容器: 使用 mcr.microsoft.com/playwright:v1.56.1-jammy,预装浏览器
  • Node.js版本: 指定Node.js 20,确保兼容性

Workflow Improvements (English)

To enhance GitHub Actions performance and security, the following optimizations have been implemented:

Performance Optimizations

  • NPM Caching: Use actions/cache to cache node_modules, speeding up dependency installation
  • Concurrency Control: Automatically cancel previous runs when new issues trigger workflow to avoid conflicts
  • Timeout Settings: Job timeout of 10 minutes to prevent hanging workflows

Version Management

  • Precise Versions: Actions use specific version numbers for reproducibility
  • Dependency Audit: Run npm audit after installation to check for security vulnerabilities

Container Configuration

  • Playwright Container: Use mcr.microsoft.com/playwright:v1.56.1-jammy with pre-installed browsers
  • Node.js Version: Specify Node.js 20 for compatibility

🤝 贡献指南

欢迎提交Issues和Pull Requests!

开发环境设置

# 1. Fork项目
# 2. 克隆到本地
git clone https://github.com/your-username/playwright_test.git

# 3. 创建功能分支
git checkout -b feature/your-feature

# 4. 进行开发和测试
npm install
npm test

# 5. 提交更改
git commit -m "feat: add new feature"
git push origin feature/your-feature

# 6. 创建Pull Request

代码规范

  • 使用ES Modules语法
  • 遵循现有代码风格
  • 添加适当的错误处理
  • 编写清晰的注释
  • 确保向后兼容

📝 更新日志

v1.0.0 (2025-11-14)

  • ✨ 初始版本发布
  • 🚀 支持GitHub Issue自动触发
  • 📄 PDF生成和存储功能
  • 💬 GitHub Issue自动回复
  • 🔔 Webhook通知支持
  • 🛡️ 完善的错误处理机制

📄 许可证

本项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情

🙏 致谢


⭐ 如果这个项目对你有帮助,请给它一个Star!

Made with ❤️ by [GitHub Actions] and [Playwright]

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published