编程语言
首页 > 编程语言> > java – 有什么方法可以提高FlyingSaucer的性能?

java – 有什么方法可以提高FlyingSaucer的性能?

作者:互联网

我已经按照this article使用FlyingSaucer将XHTML转换为PDF,它很棒,但有一个主要的垮台……它的速度非常慢!

我发现从XHTML渲染PDF需要1到2分钟,无论该页面有多简单.

基本代码:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.DocumentException;

public class FirstDoc {

    public static void main(String[] args) throws IOException, DocumentException {

        String inputFile = "firstdoc.xhtml";
        String url = new File(inputFile).toURI().toURL().toString();
        String outputFile = "firstdoc.pdf";
        OutputStream os = new FileOutputStream(outputFile);

        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(url);
        renderer.layout();
        renderer.createPDF(os);

        os.close();
    }
}

示例XHTML:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>My First Document</title>
        <style type="text/css"> b { color: green; } </style>
    </head>
    <body>
        <p>
            <b>Greetings Earthlings!</b>
            We've come for your Java.
        </p>
    </body>
</html>

有谁知道如何提高FlyingSaucer的性能?

如果不这样做,是否有人能够推荐一个替代的Java库,它有效地将PDF从URL渲染到带有外部CSS的(X)HTML文档和从URL生成的图像?

解决方法:

首先我要说的是,我使用了您的示例代码和示例xhtml,并且它“在2675ms内运行”.

我下载了flyingsaucer R8.并将三个罐放入我的类路径中.

core-renderer.jar,iText-2.0.8.jar,xml-apis-xerces-2.9.1.jar

我通过使用仪器修改代码来测量运行时间…

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.DocumentException;

public class FirstDoc {

    public static void main(String[] args) throws IOException, DocumentException {
        long start = System.currentTimeMillis();
        String inputFile = "firstdoc.xhtml";
        String url = new File(inputFile).toURI().toURL().toString();
        String outputFile = "firstdoc.pdf";
        OutputStream os = new FileOutputStream(outputFile);

        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(url);
        renderer.layout();
        renderer.createPDF(os);

        os.close();
        long end = System.currentTimeMillis();
        System.out.println("Ran in " + (end-start) + "ms");
    }
}

现在这个库并不是很快,但它似乎也没需要1-2分钟.所以现在我们需要弄清楚为什么它的运行速度如此缓慢.您能告诉我们您使用的JDK以及使用的平台吗?您还使用哪个版本的flyingsaucer?

标签:java,performance,pdf,xhtml,flying-saucer
来源: https://codeday.me/bug/20190930/1837195.html