用iTextSharp将HTML转换成PDF,ASP.NET C# 代码

本文介绍了如何利用iTextSharp库将HTML内容转换为PDF文档。首先从GitHub下载iTextSharp源码,然后在VS2010中编译生成必要的DLL文件。接着,在自己的项目中引用这些DLL,并创建一个辅助类来执行转换。需要注意的是,为了显示中文,必须设置中文字体。参考链接提供了更多关于iTextSharp转换HTML到PDF的详细信息和示例。

先去github下载源代码:https://github.com/itext/itextsharp,当前最新版本为5.5.13

解压后用vs2010打开工程文件BuildAll,生成itextsharp.xmlworker项目

生成的dll文件在src\extras\itextsharp.xmlworker\bin\Debug_woDrawing目录中

在自已的项目引入itextsharp.dll 和 itextsharp.xmlworker.dll

写一个简单的Helper类

using System;
using System.IO;

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;

public class PDFHelper {
    public static void Html2Pdf(string html, string filename) {
            using (Stream fs = new FileStream(filename, FileMode.Create)) {
                using (Document doc = new Document(PageSize.A4)) {

                    PdfWriter writer = PdfWriter.GetInstance(doc, fs);
                    doc.Open();

                    using (StringReader sr = new StringReader(html)) {
                        XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, sr);
                    }

                    doc.Close();
                    
                }
            }
        }

    }

调用:

string file = Server.MapPath("test.pdf");
string html = "<div style=\"font-family:'Microsoft YaHei';\"><a href='#last'>底部</a><h1 style='padding:1000px 0'>Hello World! 中文<br/><br/><br/><br/><br/><br/></h1><a name='last'>锚链接</a><div style='color:#0a0'>测试内容</div></div>";

PDFHelper.Html2Pdf(html, file);

注意:要设置中文字体才能显示中文,默认字体不会显示中文

 

参考:

https://stackoverflow.com/questions/25164257/how-to-convert-html-to-pdf-using-itextsharp

https://itextsupport.com/apidocs/iText5/5.5.12/

https://itextpdf.com/en/resources/examples

http://www.codexy.cn/csharp/csharp-tutorial.html

https://www.codeproject.com/Tips/899658/Create-PDF-With-Bookmark-and-TOC-from-HTML-with-iT

https://www.mikesdotnetting.com/article/84/itextsharp-links-and-bookmarks

https://acrobatusers.com/forum/javascript/change-documents-properties-intial-view-js/

评论 8
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值