生成pdf有很多种方法,用pdfbox也很方便,今天我要写的是用iText
主要在pom.xml中配置的jar包如下
<dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>4.2.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.eclipse.birt.runtime.3_7_1/com.lowagie.text --> <!--<dependency> <groupId>org.eclipse.birt.runtime.3_7_1</groupId> <artifactId>com.lowagie.text</artifactId> <version>2.1.7</version> </dependency> --> <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.11</version> </dependency> <!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.lowagie/itext-rtf --> <dependency> <groupId>com.lowagie</groupId> <artifactId>itext-rtf</artifactId> <version>2.1.7</version> </dependency>
如下代码所示,是生成pdf并且插入文字与图片
//创建pdf文件,并且写入文字跟图片 public void createPdfWithImg() { Document document = null; try { BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 设置中文字体 Font headFont = new Font(bfChinese, 10, Font.NORMAL);// 设置字体大小 document = new Document(); PdfWriter.getInstance(document, new FileOutputStream("D:/img.pdf")); //设定文档的作者 document.addAuthor("张小宁"); //测试无效 document.open(); document.add(new Paragraph("你好,Img!", headFont)); //读取一个图片 Image image = Image.getInstance("C:\Users\zhxn\Desktop\1.jpg"); //插入一个图片 document.add(image); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (document != null) { document.close(); } } }
其余都不想写了,项目中也大概就需要这些