日安,
我正在使用itext将HTML转换为PDF。但是当它调用XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);时它变慢了,当我检查JVisualVM时,似乎有一个内存泄漏。
下面是我的代码:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, baos);
document.open();
InputStream is = new ByteArrayInputStream(content.getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
document.close();
return baos.toByteArray();它在Tomcat服务器上运行。
下面是html代码:
<!--?xml version="1.0" encoding="UTF-8"?-->
<html>
<head>
<title>Title</title>
</head>
<body>
EXAMPLE
</body>
</html>
提前谢谢。
发布于 2016-08-17 17:20:42
对于Maven项目:将以下依赖项添加到项目的pom.xml文件:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf.tool/xmlworker -->
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.8</version>
</dependency> import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.poi.util.IOUtils;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
public class HtmlToPdf {
public static void main(String[] args) throws DocumentException, IOException {
File htmlFile = new File(args[0]);
String pdfFileName = "test.pdf";
Document document = new Document();
PdfWriter writer = null;
InputStream is = null;
OutputStream out = null;
if (htmlFile.exists()) {
try {
is = new FileInputStream(htmlFile);
out = new FileOutputStream(pdfFileName);
writer = PdfWriter.getInstance(document, out);
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
System.out.println("PDF Created!");
} finally {
// close the document before before input stream (is) and writer closure
if(document != null && document.isOpen()) {
document.close();
}
// no harm in closing writer here
if(writer != null) {
writer.close();
}
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(is);
}
}
}
}https://stackoverflow.com/questions/38989235
复制相似问题