吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 2509|回复: 12
收起左侧

[其他转载] 使用wkhtmltopdf第三方包将HTML转为PDF的程序

 关闭 [复制链接]
微笑小生 发表于 2021-12-22 15:25
1、这里使用的wkhtmltopdf.exe第三方包辅助(下载方式贴到最下方)


2、废话不多少直接上代码(直接运行,帖主亲自试过)


[C#] 纯文本查看 复制代码
public static bool HtmlConvertToPdf(string htmlPath, string savePath)
        {
            bool flag = false;
            CheckFilePath(savePath);

            ///这个路径为程序集的目录,因为我把应用程序 wkhtmltopdf.exe 放在了程序集同一个目录下
string exePath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "wkhtmltopdf.exe";
            if (!File.Exists(exePath))
            {
                throw new Exception("No application wkhtmltopdf.exe was found.");
            }

            try
            {
                ProcessStartInfo processStartInfo = new ProcessStartInfo();
                processStartInfo.FileName = exePath;
                processStartInfo.WorkingDirectory = Path.GetDirectoryName(exePath);
                processStartInfo.UseShellExecute = false;
                processStartInfo.CreateNoWindow = true;
                processStartInfo.RedirectStandardInput = true;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.RedirectStandardError = true;
                processStartInfo.Arguments = GetArguments(htmlPath, savePath);
                


                Process process = new Process();
                process.StartInfo = processStartInfo;
                process.Start();
                process.WaitForExit(60000);

                ///用于查看是否返回错误信息
                StreamReader srone = process.StandardError;
                StreamReader srtwo = process.StandardOutput;
                string ss1 = srone.ReadToEnd();
                string ss2 = srtwo.ReadToEnd();
                srone.Close();
                srone.Dispose();
                srtwo.Close();
                srtwo.Dispose();

                process.Close();
                process.Dispose();

                flag = true;
            }
            catch
            {
                flag = false;
            }
            return flag;
        }


private static void CheckFilePath(string savePath)
        {
            string ext = string.Empty;
            string path = string.Empty;
            string fileName = string.Empty;

            ext = Path.GetExtension(savePath);
            if (string.IsNullOrEmpty(ext) || ext.ToLower() != ".pdf")
            {
                throw new Exception("Extension error:This method is used to generate PDF files.");
            }

            fileName = Path.GetFileName(savePath);
            if (string.IsNullOrEmpty(fileName))
            {
                throw new Exception("File name is empty.");
            }

            try
            {
                path = savePath.Substring(0, savePath.IndexOf(fileName));
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch
            {
                throw new Exception("The file path does not exist.");
            }
        }

private static void CheckFilePath(string savePath)
        {
            string ext = string.Empty;
            string path = string.Empty;
            string fileName = string.Empty;

            ext = Path.GetExtension(savePath);
            if (string.IsNullOrEmpty(ext) || ext.ToLower() != ".pdf")
            {
                throw new Exception("Extension error:This method is used to generate PDF files.");
            }

            fileName = Path.GetFileName(savePath);
            if (string.IsNullOrEmpty(fileName))
            {
                throw new Exception("File name is empty.");
            }

            try
            {
                path = savePath.Substring(0, savePath.IndexOf(fileName));
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch
            {
                throw new Exception("The file path does not exist.");
            }
        }
// 在main函数直接调用HtmlConvertToPdf(htmlPath, savePath);


wkhtmltopdf.exe下载方式:
https://wkhtmltopdf.org/downloads.html   点击选择自己的版本,这里帖主选择的是win64的

本帖被以下淘专辑推荐:

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

 楼主| 微笑小生 发表于 2021-12-23 10:44
SoDump 发表于 2021-12-22 19:02
两个 CheckFilePath 函数?

复制多了一个,替换成我下方的
[C#] 纯文本查看 复制代码
  private static string GetArguments(string htmlPath, string savePath)
        {
            if (string.IsNullOrEmpty(htmlPath))
            {
                throw new Exception("HTML local path or network address can not be empty.");
            }

            if (string.IsNullOrEmpty(savePath))
            {
                throw new Exception("The path saved by the PDF document can not be empty.");
            }

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(" --page-height 100 ");        //页面高度100mm
            stringBuilder.Append(" --page-width 100 ");         //页面宽度100mm
            stringBuilder.Append(" --header-center 我是页眉 ");  //设置居中显示页眉
            stringBuilder.Append(" --header-line ");         //页眉和内容之间显示一条直线
            stringBuilder.Append(" --footer-center \"Page [page] of [topage]\" ");    //设置居中显示页脚
            stringBuilder.Append(" --footer-line ");       //页脚和内容之间显示一条直线
            stringBuilder.Append(" " + htmlPath + " ");       //本地 HTML 的文件路径或网页 HTML 的URL地址
            stringBuilder.Append(" " + savePath + " ");       //生成的 PDF 文档的保存路径
            return stringBuilder.ToString();
        }
SoDump 发表于 2021-12-23 12:38
微笑小生 发表于 2021-12-23 10:44
复制多了一个,替换成我下方的
[mw_shl_code=csharp,true]  private static string GetArguments(string ...

Good!
yunruifuzhu 发表于 2021-12-22 17:35
 楼主| 微笑小生 发表于 2021-12-22 17:50
yunruifuzhu 发表于 2021-12-22 17:35
支不支持Ajax的网页

应该可以的
SoDump 发表于 2021-12-22 19:02
两个 CheckFilePath 函数?
迷恋自留地 发表于 2021-12-23 10:53
不错哦,很棒
 楼主| 微笑小生 发表于 2021-12-23 11:39

谢谢支持
ygx0769 发表于 2021-12-24 22:41
效果图呢,能保存连续不分页的吗
 楼主| 微笑小生 发表于 2021-12-27 09:29
ygx0769 发表于 2021-12-24 22:41
效果图呢,能保存连续不分页的吗

可以自定义的文本的大小,来设置分页
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-2 05:20

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表