iText导出PDF,所需jar包如下:
itext-asian-5.2.0.jar 支持导出中文的jar包
itextpdf-5.5.9.jar PDF核心jar包
bcprov-jdk15on-147.jar PDF加密jar包 不加入则会报:org.bouncycastle.asn1.ASN1OctetString 错误。
1 import java.io.FileNotFoundException; 2 import java.io.FileOutputStream; 3 import java.io.IOException; 4 5 import com.itextpdf.text.BaseColor; 6 import com.itextpdf.text.Document; 7 import com.itextpdf.text.DocumentException; 8 import com.itextpdf.text.Element; 9 import com.itextpdf.text.Font; 10 import com.itextpdf.text.Image; 11 import com.itextpdf.text.PageSize; 12 import com.itextpdf.text.Paragraph; 13 import com.itextpdf.text.Phrase; 14 import com.itextpdf.text.pdf.BaseFont; 15 import com.itextpdf.text.pdf.PdfPCell; 16 import com.itextpdf.text.pdf.PdfPTable; 17 import com.itextpdf.text.pdf.PdfWriter; 18 19 public class JavaPdfHelloWorld { 20 public static void main(String[] args) 21 throws IOException { 22 Document document = new Document(); 23 try { 24 //中文字体 25 BaseFont bfChinese = 26 BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); 27 Font FontChinese = new Font(bfChinese, 12, Font.NORMAL); 28 //写入器 29 PdfWriter writer = PdfWriter.getInstance(document, 30 new FileOutputStream("C:\Users\hp\Desktop\HelloWorld.pdf")); 31 // 设置密码为:"World" 32 writer.setEncryption("xiaofei".getBytes(), 33 "12346".getBytes(), 34 PdfWriter.ALLOW_SCREENREADERS, 35 PdfWriter.STANDARD_ENCRYPTION_128); 36 //添加PDF属性 37 document.addTitle("小飞机的测试PDF"); 38 document.setPageSize(PageSize.A4); 39 document.addAuthor("xiaofei.xian"); 40 document.addCreationDate(); 41 document.addKeywords("xianxiaofei,xiaofei,fei,pdf,PDF,sysecho,Sysecho,SYSECHO"); 42 document.addSubject("12341234567"); 43 document.open(); 44 Paragraph pph1 = new Paragraph("因为我想活着,我不能掩藏我心中的本欲,正如我心中爱你美丽,又怎能嘴上装四大皆空。", FontChinese); 45 pph1.setSpacingAfter(50); 46 pph1.setSpacingBefore(50); 47 pph1.setFont(FontChinese); 48 document.add(pph1); 49 //读取一个图片 50 Image image = Image.getInstance("C:\Users\hp\Desktop\1.jpg"); 51 //设置图片的位置 52 image.setAbsolutePosition(50, 750); 53 //设置图片的大小 54 image.scaleAbsolute(68, 80); 55 //插入一个图片 56 document.add(image); 57 58 //表格插入 59 PdfPTable table = new PdfPTable(3); 60 table.setHorizontalAlignment(Element.ALIGN_LEFT); 61 PdfPCell cell = new PdfPCell(new Phrase("表头1", FontChinese)); 62 cell.setBackgroundColor(BaseColor.LIGHT_GRAY); 63 cell.setHorizontalAlignment(Element.ALIGN_CENTER); 64 table.addCell(cell); 65 cell.setPhrase(new Phrase("表头2", FontChinese)); 66 table.addCell(cell); 67 cell.setPhrase(new Phrase("表头3", FontChinese)); 68 table.addCell(cell); 69 table.addCell("2.1"); 70 table.addCell("2.2"); 71 table.addCell("2.3"); 72 document.add(table); 73 document.close(); 74 writer.close(); 75 System.out.println("pdf exported success!"); 76 } 77 catch (DocumentException e) { 78 e.printStackTrace(); 79 } 80 catch (FileNotFoundException e) { 81 e.printStackTrace(); 82 } 83 } 84 }