C# PuppeteerSharp html转pdf

using PuppeteerSharp.Media;
using PuppeteerSharp;

namespace Html2pdf
{
    class Program
    {
        static async Task Main(string[] args)
        {
            try
            {
                Console.WriteLine("HTML转PDF演示程序");
                Console.WriteLine("=================");

                //@page {
                //size: A5 landscape; /* A5横向 */
                //margin: 5mm;
                //}

                // 1. 准备HTML内容(模拟您的打印模板)
                string htmlContent1 = @"
<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>中药饮片库存明细表</title>
    <style>
        
    @page {
        size: 241mm 105mm landscape; /* Com10横向 */
        margin: 3mm;
    }
        body { 
            font-family: 'Microsoft YaHei', SimSun, sans-serif; 
            margin: 20px; 
            font-size: 14px;
        }
        .header { 
            text-align: center; 
            margin-bottom: 30px;
        }
        .title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #000;
            padding: 8px;
            text-align: center;
        }
        th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
        .footer {
            margin-top: 30px;
            text-align: center;
            font-size: 12px;
        }
        .signature-area {
            margin-top: 40px;
            display: flex;
            justify-content: space-between;
        }
        .signature {
            width: 18%;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class='header'>
        <div class='title'>在库中药饮片明细</div>
        <div>单据编号: ZY-20230001</div>
        <div>打印日期: 2023-11-16 14:30:25</div>
    </div>
    
    <div>
        <div>仓库信息: 中药仓库-001</div>
        <div>温控要求: 常温10-30摄氏度  相对湿度:35%-75%</div>
        <div>仓库地址: 四川省成都市某某某某某公司</div>
    </div>
    
    <table>
        <thead>
            <tr>
                <th>序号</th>
                <th>品名</th>
                <th>规格</th>
                <th>生产厂家</th>
                <th>批号</th>
                <th>数量</th>
                <th>单价</th>
                <th>金额</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>当归片(酒炙)</td>
                <td>10g/袋</td>
                <td>安徽某某某某某某某公司</td>
                <td>DG-202309</td>
                <td>120袋</td>
                <td>¥15.80</td>
                <td>¥1896.00</td>
            </tr>
            <tr>
                <td>2</td>
                <td>黄芪</td>
                <td>500g/包</td>
                <td>甘肃某某某某某某某基地</td>
                <td>HQ-202308</td>
                <td>30包</td>
                <td>¥86.50</td>
                <td>¥2595.00</td>
            </tr>
            <tr>
                <td>3</td>
                <td>金银花</td>
                <td>250g/罐</td>
                <td>山东某某某某某合作社</td>
                <td>JYH-202307</td>
                <td>45罐</td>
                <td>¥58.20</td>
                <td>¥2619.00</td>
            </tr>
        </tbody>
    </table>
    
    <div style='margin-top: 20px;'>
        <div>合计金额(大写): 贰万捌仟叁佰捌拾壹元陆角整</div>
        <div>合计金额(小写): ¥28381.60</div>
    </div>
    
    <div class='signature-area'>
        <div class='signature'>开票人: 刘开票</div>
        <div class='signature'>备货人: 李备货</div>
        <div class='signature'>复核人: 王复核</div>
        <div class='signature'>发货人: 张发货</div>
        <div class='signature'>收货人: __________</div>
    </div>
    
    <div class='footer'>
        <div>客服电话: 888-888-8888</div>
        <div>© 2023 中药管理系统</div>
    </div>
</body>
</html>";

                // 1. 定义文件路径
                string filePath = @"D:\test3.html";

                // 2. 检查文件是否存在
                if (!File.Exists(filePath))
                {
                    Console.WriteLine("错误: 文件不存在!");
                    return;
                }

                // 3. 读取文件内容
                string htmlContent = File.ReadAllText(filePath);

                // 4. 输出内容长度验证
                Console.WriteLine($"成功读取文件,内容长度: {htmlContent.Length}字符");

                // 5. 这里可以继续处理htmlContent,比如传递给PuppeteerSharp生成PDF
                // GeneratePdf(htmlContent);


                // 2. 获取输出PDF路径
                //Console.Write("请输入输出PDF路径(默认: output.pdf): ");
                string pdfOutputPath = "D:\\output1.pdf";
                if (string.IsNullOrWhiteSpace(pdfOutputPath))
                {
                    pdfOutputPath = "output.pdf";
                }

                Console.WriteLine("正在转换HTML为PDF...");

                // 3. 初始化浏览器实例
                var browser = await InitializeBrowser();

                // 4. 生成PDF
                var pdfBytes = await GeneratePdf(browser, htmlContent);

                // 5. 保存PDF文件
                await File.WriteAllBytesAsync(pdfOutputPath, pdfBytes);

                Console.WriteLine($"转换完成! PDF已保存到: {Path.GetFullPath(pdfOutputPath)}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }

            Console.WriteLine("按任意键退出...");
            Console.ReadKey();
        }

        static async Task<IBrowser> InitializeBrowser()
        {
            Console.WriteLine("您可以手动下载Chromium并指定路径");
            //Console.Write("请输入本地Chrome/Chromium路径: ");
            var path = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe";
            return await Puppeteer.LaunchAsync(new LaunchOptions
            {
                ExecutablePath = path,
                Headless = true
            });
        }

        static async Task<byte[]> GeneratePdf(IBrowser browser, string htmlContent)
        {
            using var page = await browser.NewPageAsync();

            // 设置HTML内容
            await page.SetContentAsync(htmlContent, new NavigationOptions
            {
                WaitUntil = new[] { WaitUntilNavigation.Networkidle0 },
                Timeout = 30000
            });

            // 生成PDF选项
            var pdfOptions = new PdfOptions
            {
                Format = PaperFormat.A4,
                PrintBackground = true,
                MarginOptions = new MarginOptions
                {
                    Top = "20mm",
                    Right = "20mm",
                    Bottom = "20mm",
                    Left = "20mm"
                },
                Scale = 0.7m
            };

            //var pdfOptions = new PdfOptions
            //{
            //    Width = "148mm",  // A5宽度
            //    Height = "210mm", // A5高度
            //    Landscape = true, // 设置为横向
            //    PrintBackground = true,
            //    MarginOptions = new MarginOptions
            //    {
            //        Top = "10mm",
            //        Right = "10mm",
            //        Bottom = "10mm",
            //        Left = "10mm"
            //    }
            //};

            //var pdfOptions = new PdfOptions
            //{
            //    // 设置A5横向尺寸(148mm × 210mm)
            //    Width = "210mm",  // 横向时宽度为210mm
            //    Height = "148mm", // 横向时高度为148mm
            //    Landscape = true, // 横向模式
            //    PrintBackground = true,
            //    MarginOptions = new MarginOptions
            //    {
            //        Top = "5mm",
            //        Right = "5mm",
            //        Bottom = "5mm",
            //        Left = "5mm"
            //    },
            //    Scale = 0.8m, // 确保不缩放
            //    PreferCSSPageSize = true // 使用CSS中定义的页面尺寸
            //};

            //var pdfOptions = new PdfOptions
            //{
            //    // 设置Com10横向尺寸(241mm × 105mm)
            //    Width = "241mm",  // 横向时宽度为241mm
            //    Height = "105mm", // 横向时高度为105mm
            //    Landscape = false, // 横向模式
            //    PrintBackground = true,
            //    MarginOptions = new MarginOptions
            //    {
            //        Top = "3mm",
            //        Right = "3mm",
            //        Bottom = "3mm",
            //        Left = "3mm"
            //    },
            //    Scale = 0.7m, // 建议保持1.0不缩放
            //    PreferCSSPageSize = false // 使用代码中定义的尺寸
            //};

            return await page.PdfDataAsync(pdfOptions);
        }
    }
}

 

posted @ 2025-11-14 10:00  摩诘  阅读(5)  评论(0)    收藏  举报