相关疑难解决方法(0)

使用iText将HTML转换为PDF

我发布这个问题是因为许多开发人员以不同的形式提出或多或少相同的问题.我将自己回答这个问题(我是iText集团的创始人/首席技术官),因此它可以成为"维基答案".如果Stack Overflow"文档"功能仍然存在,那么这将是文档主题的一个很好的候选者.

源文件:

我想将以下HTML文件转换为PDF:

<html>
    <head>
        <title>Colossal (movie)</title>
        <style>
            .poster { width: 120px;float: right; }
            .director { font-style: italic; }
            .description { font-family: serif; }
            .imdb { font-size: 0.8em; }
            a { color: red; }
        </style>
    </head>
    <body>
        <img src="img/colossal.jpg" class="poster" />
        <h1>Colossal (2016)</h1>
        <div class="director">Directed by Nacho Vigalondo</div>
        <div class="description">Gloria is an out-of-work party girl
            forced to leave her life in New York City, and move back home.
            When reports surface that a giant creature is destroying Seoul,
            she …
Run Code Online (Sandbox Code Playgroud)

html pdf pdf-generation itext xmlworker

10
推荐指数
2
解决办法
2万
查看次数

如何使用iText将带图像和超链接的HTML转换为PDF?

我想转换HTMLPDF在使用iTextSharp的ASP.NET同时使用Web应用程序的MVC, 网页形式.在<img><a>元素有绝对和相对 URL和一些的<img>元素的base64.典型的答案在这里SO和谷歌搜索结果中使用泛型HTMLPDF的代码XMLWorkerHelper看起来是这样的:

using (var stringReader = new StringReader(xHtml))
{
    using (Document document = new Document())
    {
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        document.Open();
        XMLWorkerHelper.GetInstance().ParseXHtml(
            writer, document, stringReader
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

所以这样的样本HTML:

<div>
    <h3>HTML Works, but Broken in Converted PDF</h3>
    <div>Relative local <img>: <img src='./../content/images/kuujinbo_320-30.gif' /></div>
    <div>
        Base64 <img>:
        <img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' />
    </div>
    <div><a …
Run Code Online (Sandbox Code Playgroud)

pdf itext html-parsing html-agility-pack xmlworker

5
推荐指数
1
解决办法
7358
查看次数