使用iText将HTML转换为PDF

Bru*_*gie 10 html pdf pdf-generation itext xmlworker

我发布这个问题是因为许多开发人员以不同的形式提出或多或少相同的问题.我将自己回答这个问题(我是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 gradually comes to the realization that she is somehow connected
            to this phenomenon.
        </div>
        <div class="imdb">Read more about this movie on
            <a href="www.imdb.com/title/tt4680182">IMDB</a>
        </div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

在浏览器中,此HTML如下所示:

在此输入图像描述

我遇到的问题:

HTMLWorker根本不考虑CSS

当我使用时HTMLWorker,我需要创建一个ImageProvider以避免错误,通知我无法找到图像.我还需要创建一个StyleSheet实例来改变一些样式:

public static class MyImageFactory implements ImageProvider {
    public Image getImage(String src, Map<String, String> h,
            ChainedProperties cprops, DocListener doc) {
        try {
            return Image.getInstance(
                String.format("resources/html/img/%s",
                    src.substring(src.lastIndexOf("/") + 1)));
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }    
}

public static void main(String[] args) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream("results/htmlworker.pdf"));
    document.open();
    StyleSheet styles = new StyleSheet();   
    styles.loadStyle("imdb", "size", "-3");
    HTMLWorker htmlWorker = new HTMLWorker(document, null, styles);
    HashMap<String,Object> providers = new HashMap<String, Object>();
    providers.put(HTMLWorker.IMG_PROVIDER, new MyImageFactory());
    htmlWorker.setProviders(providers);
    htmlWorker.parse(new FileReader("resources/html/sample.html"));
    document.close();   
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

在此输入图像描述

出于某种原因,HTMLWorker还会显示<title>标签的内容.我不知道如何避免这种情况.标题中的CSS根本没有被解析,我必须使用该StyleSheet对象在我的代码中定义所有样式.

当我查看我的代码时,我发现我正在使用的大量对象和方法已被弃用:

在此输入图像描述

所以我决定升级到使用XML Worker.


使用XML Worker时找不到图像

我尝试了以下代码:

public static final String DEST = "results/xmlworker1.pdf";
public static final String HTML = "resources/html/sample.html";
public void createPdf(String file) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
    document.open();
    XMLWorkerHelper.getInstance().parseXHtml(writer, document,
            new FileInputStream(HTML));
    document.close();
}
Run Code Online (Sandbox Code Playgroud)

这导致以下PDF:

在此输入图像描述

而不是Times-Roman,使用默认字体Helvetica; 这是iText的典型特征(我应该在我的HTML中明确定义一种字体).否则,CSS似乎得到尊重,但图像丢失,我没有收到错误消息.

有了HTMLWorker,抛出异常,我能够通过引入一个来解决问题ImageProvider.让我们看看这是否适用于XML Worker.

并非XML Worker中支持所有CSS样式

我改编了这样的代码:

public static final String DEST = "results/xmlworker2.pdf";
public static final String HTML = "resources/html/sample.html";
public static final String IMG_PATH = "resources/html/";
public void createPdf(String file) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
    document.open();

    CSSResolver cssResolver =
            XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
    HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
    htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
    htmlContext.setImageProvider(new AbstractImageProvider() {
        public String getImageRootPath() {
            return IMG_PATH;
        }
    });

    PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
    HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
    CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

    XMLWorker worker = new XMLWorker(css, true);
    XMLParser p = new XMLParser(worker);
    p.parse(new FileInputStream(HTML));

    document.close();
}
Run Code Online (Sandbox Code Playgroud)

我的代码更长,但现在渲染图像:

在此输入图像描述

图像比我使用HTMLWorker它时更大,这告诉我考虑widthposter类的CSS属性,但float忽略了该属性.我该如何解决?

剩下的问题是:

所以问题归结为:我有一个特定的 HTML文件,我尝试转换为PDF.我经历了很多工作,一个接一个地解决了一个问题,但是有一个我无法解决的具体问题:我如何让iText尊重定义元素位置的CSS,比如float: right

附加问题:

当我的HTML包含表单元素(例如<input>)时,将忽略这些表单元素.

Bru*_*gie 14

为什么你的代码不起作用

作为引进的解释HTML到PDF格式的教程,HTMLWorker已经在很多年前弃用.它无意转换完整的HTML页面.它不知道HTML页面有a <head><body>section; 它只是解析所有内容.它旨在解析小的HTML片段,您可以使用StyleSheet该类定义样式; 真正的CSS不受支持.

然后是XML Worker.XML Worker是一种解析XML的通用框架.作为概念证明,我们决定将一些XHTML写入PDF功能,但我们不支持所有HTML标记.例如:表单根本不受支持,并且很难支持用于定位内容的CSS.HTML中的表单与PDF中的表单非常不同.iText架构与HTML + CSS架构之间也存在不匹配.渐渐地,我们扩展了XML Worker,主要是基于客户的请求,但XML Worker变成了一个有许多触角的怪物.

最终,我们决定从头开始重写iText,并考虑到HTML + CSS转换的要求.这导致了iText 7.在iText 7之上,我们创建了几个附加组件,在这个上下文中最重要的是pdfHTML.

如何解决问题

使用最新版本的iText(iText 7.1.0 + pdfHTML 2.0.0),将HTML从问题转换为PDF的代码简化为以下代码段:

public static final String SRC = "src/main/resources/html/sample.html";
public static final String DEST = "target/results/sample.pdf";
public void createPdf(String src, String dest) throws IOException {
    HtmlConverter.convertToPdf(new File(src), new File(dest));
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

在此输入图像描述

如您所见,这几乎是您期望的结果.自iText 7.1.0/pdfHTML 2.0.0起,默认字体为Times-Roman.CSS正在受到尊重:图像现在浮动在右侧.

一些额外的想法.

当我提出升级到iText 7/pdfHTML 2的建议时,开发人员常常反对升级到更新的iText版本.请允许我回答我听到的前三个论点:

我需要使用免费的iText,iText 7不是免费的/ pdfHTML插件是封闭源.

iText 7使用AGPL发布,就像iText 5和XML Worker一样.该AGPL允许免费使用的感免费的开源项目的背景下.如果您要分发封闭源/专有产品(例如,您在SaaS环境中使用iText),则不能免费使用iText; 在这种情况下,您必须购买商业许可证.对于iText 5来说,情况已经如此; 这对iText 7来说仍然如此.对于iText 5之前的版本:你根本不应该使用它们.关于pdfHTML:第一个版本确实只能作为闭源软件使用.我们在iText集团内部进行了大量讨论:一方面,有些人希望避免那些不听取开发人员的公司的大规模滥用,因为那些开发人员告诉他们开源的权力不是和免费一样.开发商告诉我们,他们的老板强迫他们做错事,他们无法说服老板购买商业许可证.另一方面,有人认为我们不应该因为老板的错误行为而惩罚开发商.最终,支持开源pdfHTML的人,即iText的开发者,赢得了争论.请证明它们没有错,并正确使用iText:如果您免费使用iText ,请尊重AGPL ; 如果您在封闭的源环境中使用iText,请确保您的老板购买了商业许可证.

我需要维护一个遗留系统,我必须使用旧的iText版本.

真的吗?维护还涉及应用升级和迁移到您正在使用的软件的新版本.如您所见,使用iText 7和pdfHTML时所需的代码非常简单,并且比以前需要的代码更不容易出错.迁移项目不应该花太长时间.

我刚刚开始,我不知道iText 7; 我完成项目后才发现.

这就是我发布这个问题和答案的原因.把自己想象成一个极端程序员.扔掉所有代码,然后重新开始.你会注意到它并没有你想象的那么多,而且你知道你已经让你的项目面向未来,因为iText 5正在逐步淘汰,你会睡得更好.我们仍然向付费客户提供支持,但最终,我们将完全停止支持iText 5.


Abh*_*pta 8

使用 iText 7 和以下代码:

public void generatePDF(String htmlFile) {
    try {

        //HTML String
        String htmlString = htmlFile;
        //Setting destination 
        FileOutputStream fileOutputStream = new FileOutputStream(new File(dirPath + "/USER-16-PF-Report.pdf"));
        
        PdfWriter pdfWriter = new PdfWriter(fileOutputStream);
        ConverterProperties converterProperties = new ConverterProperties();
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);

        //For setting the PAGE SIZE
        pdfDocument.setDefaultPageSize(new PageSize(PageSize.A3));
        
        Document document = HtmlConverter.convertToDocument(htmlFile, pdfDocument, converterProperties);
        document.close();
    } 
    catch (Exception e) {
         e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)