依赖
<!-- pdf:start --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.11</version> </dependency> <dependency> <groupId>com.itextpdf.tool</groupId> <artifactId>xmlworker</artifactId> <version>5.5.11</version> </dependency> <!-- 支持中文 --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency> <!-- 支持css样式渲染 --> <dependency> <groupId>org.xhtmlrenderer</groupId> <artifactId>flying-saucer-pdf-itext5</artifactId> <version>9.1.16</version> </dependency> <!-- 转换html为标准xhtml包 --> <dependency> <groupId>net.sf.jtidy</groupId> <artifactId>jtidy</artifactId> <version>r938</version> </dependency> <!-- pdf:end -->
使用示例
1、简单使用
package com.pengshiyu; import com.itextpdf.text.Document; import com.itextpdf.text.Font; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileOutputStream; /** * Hello world! */ public class PdfDemo { public static void main(String[] args) throws Exception { // 新建文档 Document document = new Document(PageSize.A4); // 如果输出中文,需要设置中文字体 BaseFont chineseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); Font font = new Font(chineseFont, 12, Font.NORMAL); PdfWriter.getInstance(document, new FileOutputStream("hello.pdf")); // 打开文档 document.open(); // 写入内容 Paragraph paragraph = new Paragraph("hello world 你好世界", font); document.add(paragraph); // 关闭文档 document.close(); } }
2、稍复杂的示例
package com.pengshiyu; import com.itextpdf.text.*; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.codec.Base64; import com.itextpdf.tool.xml.XMLWorker; import com.itextpdf.tool.xml.XMLWorkerFontProvider; import com.itextpdf.tool.xml.css.StyleAttrCSSResolver; import com.itextpdf.tool.xml.html.CssAppliers; import com.itextpdf.tool.xml.html.CssAppliersImpl; import com.itextpdf.tool.xml.html.Tags; import com.itextpdf.tool.xml.parser.XMLParser; import com.itextpdf.tool.xml.pipeline.css.CSSResolver; import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline; import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline; import com.itextpdf.tool.xml.pipeline.html.AbstractImageProvider; import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline; import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext; import java.io.*; public class App { /** * 创建PDF文件 * * @param htmlStr * @throws Exception */ private static void writeToOutputStreamAsPDF(String htmlStr) throws Exception { String targetFile = "pdfDemo.pdf"; File targeFile = new File(targetFile); if (targeFile.exists()) { targeFile.delete(); } //定义pdf文件尺寸,采用A4横切 Document document = new Document(PageSize.A4, 25, 25, 15, 40);// 左、右、上、下间距 //定义输出路径 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(targetFile)); // PdfReportHeaderFooter header = new PdfReportHeaderFooter("", 8, PageSize.A4); // writer.setPageEvent(header); writer.addViewerPreference(PdfName.PRINTSCALING, PdfName.NONE); document.open(); // CSS CSSResolver cssResolver = new StyleAttrCSSResolver(); CssAppliers cssAppliers = new CssAppliersImpl(new XMLWorkerFontProvider() { @Override public Font getFont(String fontname, String encoding, boolean embedded, float size, int style, BaseColor color) { try { //用于中文显示的Provider BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); return new Font(bfChinese, size, style); } catch (Exception e) { return super.getFont(fontname, encoding, size, style); } } }); //html HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers); htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory()); htmlContext.setImageProvider(new AbstractImageProvider() { @Override public Image retrieve(String src) { //支持图片显示 int pos = src.indexOf("base64,"); try { if (src.startsWith("data") && pos > 0) { byte[] img = Base64.decode(src.substring(pos + 7)); return Image.getInstance(img); } else if (src.startsWith("http")) { return Image.getInstance(src); } } catch (BadElementException ex) { return null; } catch (IOException ex) { return null; } return null; } @Override public String getImageRootPath() { return null; } }); // Pipelines PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer); HtmlPipeline html = new HtmlPipeline(htmlContext, pdf); CssResolverPipeline css = new CssResolverPipeline(cssResolver, html); // XML Worker XMLWorker worker = new XMLWorker(css, true); XMLParser p = new XMLParser(worker); p.parse(new ByteArrayInputStream(htmlStr.getBytes())); document.close(); } /** * 读取 HTML 文件 * * @return */ private static String readHtmlFile() { StringBuffer textHtml = new StringBuffer(); try { File file = new File("printDemo.html"); BufferedReader reader = new BufferedReader(new FileReader(file)); String tempString = null; // 一次读入一行,直到读入null为文件结束 while ((tempString = reader.readLine()) != null) { textHtml.append(tempString); } reader.close(); } catch (IOException e) { return null; } return textHtml.toString(); } public static void main(String[] args) throws Exception { // 读取html文件 String htmlStr = readHtmlFile(); // 将html文件转成PDF writeToOutputStreamAsPDF(htmlStr); } }
<html> <head></head> <body> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>出库单</title> <div> <div> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td height="40" colspan="2"><h3 style="font-weight: bold; text-align: center; letter-spacing: 5px; font-size: 24px;">入库单</h3></td> <td width="12%" height="20" rowspan="2"> <img style="width: 105px;height: 105px;" src="data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAH0AAAB9AQAAAACn+1GIAAAAqElEQVR42u3VMQ7DMAwDQP6A//8lx24qKRRw0s1yu8Uw4OQGIaHsBHUfLzzwAxCAInoZg6dI9dUUBIOyHEG56CmodAaxwtfbboLTVWpeU9+EDAH37m9CmkTYxDGUE0agMIakk3y4Ut8G37iom02M4bPniHWAtqFDTjjSGLrZvXAOmTnL1124C73r6Yo8Ane61k6eQeVjIM2h482D1RwScrpNjuH5R/0b3s6ZZNyKlt3iAAAAAElFTkSuQmCC" /> </td> </tr> <tr> <td width="50%" height="30">操作人:xxx</td> <td width="50%" height="30" colspan="2">创建时间:2021-09-14 12:00:00</td> </tr> </tbody> </table> </div> <div style="margin-top: 5px; margin-bottom: 6px; margin-left: 4px"></div> <div> <table width="100%" style="border-collapse: collapse; border-spacing: 0;border:0px;"> <tr style="height: 25px;"> <td style="background: #eaeaea; text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;" width="10%">序号</td> <td style="background: #eaeaea; text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;" width="30%">商品</td> <td style="background: #eaeaea; text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;" width="30%">单位</td> <td style="background: #eaeaea; text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-right: 1px solid #000000;" width="30%">数量</td> </tr> <tr> <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">1</td> <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">xxx沐浴露</td> <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">箱</td> <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-right: 1px solid #000000;">3</td> </tr> <tr> <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">2</td> <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">xxx洗发水</td> <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">箱</td> <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-right: 1px solid #000000;">4</td> </tr> <tr> <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">3</td> <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">xxx洗衣粉</td> <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">箱</td> <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-right: 1px solid #000000;">5</td> </tr> <tr> <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-bottom: 1px solid #000000;">4</td> <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-bottom: 1px solid #000000;">xxx洗面奶</td> <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-bottom: 1px solid #000000;">箱</td> <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-right: 1px solid #000000; border-bottom: 1px solid #000000;">5</td> </tr> </table> </div> </div> </body> </html>
参考