java itextpdf-55133jar将页面导出成pdf
以下是使用itextpdf库将页面导出成pdf的示例代码:
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
public class HtmlToPdfConverter {
public static void main(String[] args) {
String htmlFile = "example.html";
String pdfFile = "example.pdf";
convert(htmlFile, pdfFile);
}
public static void convert(String htmlFile, String pdfFile) {
Document document = new Document(PageSize.LETTER);
try {
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
document.open();
XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document, HtmlToPdfConverter.class.getResourceAsStream(htmlFile));
document.close();
System.out.println("PDF file generated successfully!");
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
}
}
说明:
- 首先需要引入itextpdf库,版本为5.5.13.3;
- 创建一个Document对象,并指定页面大小为Letter;
- 创建PdfWriter对象,将Document对象和输出文件流作为参数传入;
- 调用Document对象的open()方法,打开文档;
- 使用XMLWorkerHelper类的parseXHtml()方法,将HTML文件转换为PDF格式;
- 调用Document对象的close()方法,关闭文档;
- 输出生成成功的信息。
注意:本示例代码中的HTML文件需要与Java类在同一目录下,并且文件名需要与示例代码中的文件名相同。如果HTML文件不在同一目录下,需要使用文件的绝对路径或相对路径作为参数传入getResourceAsStream()方法中
原文地址: https://www.cveoy.top/t/topic/eEJ9 著作权归作者所有。请勿转载和采集!