我在Java中使用iText将HTML转换为PDF。
我想要一个特定的段落,其中有一些单词是Bold,有些是Bold+Underlined,它作为字符串传递给iText代码,并使用iText库转换为PDF。
我找不到合适的方法。我该怎么做?
发布于 2014-06-04 12:08:32
如果要将XHTML转换为PDF,则需要iText + XML。
您可以在这里找到一些示例:http://itextpdf.com/sandbox/xmlworker
最简单的例子如下:
public void createPdf(String file) throws IOException, DocumentException {
// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// step 3
document.open();
// step 4
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new FileInputStream(HTML));
// step 5
document.close();
}请注意,在本例中,HTML文件是作为FileInputStream传递的。你想要传递一个String。这意味着你必须这样做:
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new StringReader("<p>The <b>String</b> I want to render to PDF</p>"));在Sandbox中有更复杂的例子,以防您需要对图像、特殊字体等的支持。例如,这个例子将将XHTML转换为一系列iText对象,而不是将它们呈现给页面右转。
https://stackoverflow.com/questions/24036662
复制相似问题