编程爱好者联盟 2016-11-06
iText是著名的开放项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。
官方网站:http://itextpdf.com/
示例版本:itextpdf-5.2.1.jar
Rectangle rect = new Rectangle(PageSize.B5.rotate()); //页面大小 rect.setBackgroundColor(BaseColor.ORANGE); //页面背景色 Document doc = new Document(rect); PdfWriter writer = PdfWriter.getInstance(doc, out); writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2); //PDF版本(默认1.4) /* 设置密码 */ writer.setEncryption("Hello".getBytes(), "World".getBytes(), PdfWriter.ALLOW_SCREENREADERS, PdfWriter.STANDARD_ENCRYPTION_128); /* PDF属性 */ doc.addTitle("Title@sample"); doc.addAuthor("Author@rensanning"); doc.addSubject("Subject@iText sample"); doc.addKeywords("Keywords@iText"); doc.addCreator("Creator@iText"); doc.setMargins(10, 20, 30, 40); doc.open(); doc.add(new Paragraph("Hello World")); //在此处追加内容 document.close();
document.add(new Paragraph("First page")); document.add(new Paragraph(Document.getVersion())); document.newPage(); writer.setPageEmpty(false); document.newPage(); document.add(new Paragraph("New page"));
/* 图片水印 */ PdfReader reader = new PdfReader(FILE_DIR + "setWatermark.pdf"); PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR + "setWatermark2.pdf")); Image img = Image.getInstance("resource/watermark.jpg"); img.setAbsolutePosition(200, 400); PdfContentByte under = stamp.getUnderContent(1); under.addImage(img); /* 文字水印 */ PdfContentByte over = stamp.getOverContent(2); over.beginText(); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,BaseFont.EMBEDDED); over.setFontAndSize(bf, 18); over.setTextMatrix(30, 30); over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE", 230, 430, 45); over.endText(); /* 背景图 */ Image img2 = Image.getInstance("resource/test.jpg"); img2.setAbsolutePosition(0, 0); PdfContentByte under2 = stamp.getUnderContent(3); under2.addImage(img2); stamp.close(); reader.close();
/* Chunk对象: a String, a Font, and some attributes */ document.add(new Chunk("China")); document.add(new Chunk(" ")); Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE); Chunk id = new Chunk("chinese", font); id.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f); id.setTextRise(6); document.add(id); document.add(Chunk.NEWLINE); document.add(new Chunk("Japan")); document.add(new Chunk(" ")); Font font2 = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE); Chunk id2 = new Chunk("japanese", font2); id2.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f); id2.setTextRise(6); id2.setUnderline(0.2f, -2f); document.add(id2); document.add(Chunk.NEWLINE); /* Phrase对象: a List of Chunks with leading */ document.newPage(); document.add(new Phrase("Phrase page")); Phrase director = new Phrase(); Chunk name = new Chunk("China"); name.setUnderline(0.2f, -2f); director.add(name); director.add(new Chunk(",")); director.add(new Chunk(" ")); director.add(new Chunk("chinese")); director.setLeading(24); document.add(director); Phrase director2 = new Phrase(); Chunk name2 = new Chunk("Japan"); name2.setUnderline(0.2f, -2f); director2.add(name2); director2.add(new Chunk(",")); director2.add(new Chunk(" ")); director2.add(new Chunk("japanese")); director2.setLeading(24); document.add(director2); /* Paragraph对象: a Phrase with extra properties and a newline */ document.newPage(); document.add(new Paragraph("Paragraph page")); Paragraph info = new Paragraph(); info.add(new Chunk("China ")); info.add(new Chunk("chinese")); info.add(Chunk.NEWLINE); info.add(new Phrase("Japan ")); info.add(new Phrase("japanese")); document.add(info); /* List对象: a sequence of Paragraphs called ListItem */ document.newPage(); List list = new List(List.ORDERED); for (int i = 0; i < 10; i++) { ListItem item = new ListItem( String.format("%s: %d movies","country" + (i + 1), (i + 1) * 100), new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE)); List movielist = new List(List.ORDERED, List.ALPHABETICAL); movielist.setLowercase(List.LOWERCASE); for (int j = 0; j < 5; j++) { ListItem movieitem = new ListItem("Title" + (j + 1)); List directorlist = new List(List.UNORDERED); for (int k = 0; k < 3; k++) { directorlist.add(String.format("%s, %s", "Name1" + (k + 1),"Name2" + (k + 1))); } movieitem.add(directorlist); movielist.add(movieitem); } item.add(movielist); list.add(item); } document.add(list); /* Anchor对象: internal and external links */ document.newPage(); Paragraph country = new Paragraph(); Anchor dest = new Anchor("china", new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE)); dest.setName("CN"); dest.setReference("http://www.china.com");//external country.add(dest); country.add(String.format(": %d sites", 10000)); document.add(country); document.newPage(); Anchor toUS = new Anchor("Go to first page.", new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE)); toUS.setReference("#CN");//internal document.add(toUS); /* Image对象 */ document.newPage(); Image img = Image.getInstance("resource/test.jpg"); img.setAlignment(Image.LEFT | Image.TEXTWRAP); img.setBorder(Image.BOX); img.setBorderWidth(10); img.setBorderColor(BaseColor.WHITE); img.scaleToFit(1000, 72);//大小 img.setRotationDegrees(-30);//旋转 document.add(img); /* Chapter, Section对象(目录) */ document.newPage(); Paragraph title = new Paragraph("Title"); Chapter chapter = new Chapter(title, 1); title = new Paragraph("Section A"); Section section = chapter.addSection(title); section.setBookmarkTitle("bmk"); section.setIndentation(30); section.setBookmarkOpen(false); section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT); Section subsection = section.addSection(new Paragraph("Sub Section A")); subsection.setIndentationLeft(20); subsection.setNumberDepth(1); document.add(chapter);
/* 左右箭头 */ document.add(new VerticalPositionMark() { public void draw(PdfContentByte canvas, float llx, float lly, float urx, float ury, float y) { canvas.beginText(); BaseFont bf = null; try { bf = BaseFont.createFont(BaseFont.ZAPFDINGBATS, "", BaseFont.EMBEDDED); } catch (Exception e) {} canvas.setFontAndSize(bf, 12); /* LEFT */ canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), llx - 10, y, 0); /* RIGHT */ canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), urx + 10, y + 8, 180); canvas.endText(); } }); /* 直线 */ Paragraph p1 = new Paragraph("LEFT"); p1.add(new Chunk(new LineSeparator())); p1.add("R"); document.add(p1); /* 点线 */ Paragraph p2 = new Paragraph("LEFT"); p2.add(new Chunk(new DottedLineSeparator())); p2.add("R"); document.add(p2); /* 下滑线 */ LineSeparator UNDERLINE = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2); Paragraph p3 = new Paragraph("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN"); p3.add(UNDERLINE);
Paragraph p = new Paragraph("段落内容"); /* 对齐方式 */ p.setAlignment(Element.ALIGN_JUSTIFIED); /* 缩进 */ p.setIndentationLeft(1 * 15f); p.setIndentationRight((5 - 1) * 15f); /* 间距 */ p.setSpacingAfter(15f); p.setSpacingBefore(15f);
/* 删除页 */ PdfReader reader = new PdfReader(FILE_DIR + "deletePage.pdf"); reader.selectPages("1,3"); PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR + "deletePage2.pdf")); stamp.close(); reader.close(); /* 插入页 */ PdfReader reader = new PdfReader(FILE_DIR + "insertPage.pdf"); PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR+ "insertPage2.pdf")); stamp.insertPage(2, reader.getPageSize(1)); stamp.close(); reader.close(); /* 页排序 */ PdfWriter writer = PdfWriter.getInstance(doc, out); writer.setLinearPageMode(); doc.open(); doc.add(new Paragraph("1 page")); doc.newPage(); doc.add(new Paragraph("2 page")); doc.newPage(); doc.add(new Paragraph("3 page")); doc.newPage(); doc.add(new Paragraph("4 page")); doc.newPage(); doc.add(new Paragraph("5 page")); int[] order = {4,3,2,1}; writer.reorderPages(order);
/* 添加一些Page */ document.newPage(); document.add(new Chunk("Chapter 1").setLocalDestination("1")); document.newPage(); document.add(new Chunk("Chapter 2").setLocalDestination("2")); document.add(new Paragraph(new Chunk("Sub 2.1").setLocalDestination("2.1"))); document.add(new Paragraph(new Chunk("Sub 2.2").setLocalDestination("2.2"))); document.newPage(); document.add(new Chunk("Chapter 3").setLocalDestination("3")); /* 生成大纲 */ PdfContentByte cb = writer.getDirectContent(); PdfOutline root = cb.getRootOutline(); PdfOutline oline1 = new PdfOutline(root, PdfAction.gotoLocalPage("1", false), "Chapter 1"); PdfOutline oline2 = new PdfOutline(root, PdfAction.gotoLocalPage("2", false), "Chapter 2"); PdfOutline oline2_1 = new PdfOutline(oline2, PdfAction.gotoLocalPage("2.1", false), "Sub 2.1"); PdfOutline oline2_2 = new PdfOutline(oline2, PdfAction.gotoLocalPage("2.2", false), "Sub 2.2"); PdfOutline oline3 = new PdfOutline(root, PdfAction.gotoLocalPage("3", false), "Chapter 3");
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + "setHeaderFooter.pdf")); writer.setPageEvent(new PdfPageEventHelper() { public void onEndPage(PdfWriter writer, Document document) { PdfContentByte cb = writer.getDirectContent(); cb.saveState(); cb.beginText(); BaseFont bf = null; try { bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); } catch (Exception e) {} cb.setFontAndSize(bf, 10); /* Header,分左中右 */ float x = document.top(-20); cb.showTextAligned(PdfContentByte.ALIGN_LEFT,"H-Left",document.left(), x, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, writer.getPageNumber()+ " page", (document.right() + document.left())/2, x, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT,"H-Right",document.right(), x, 0); /* Footer,分左中右 */ float y = document.bottom(-20); cb.showTextAligned(PdfContentByte.ALIGN_LEFT,"F-Left",document.left(), y, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, writer.getPageNumber()+" page", (document.right() + document.left())/2, y, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT,"F-Right",document.right(), y, 0); cb.endText(); cb.restoreState(); } });
PdfWriter writer = PdfWriter.getInstance(doc, out); writer.setPdfVersion(PdfWriter.VERSION_1_5); writer.setViewerPreferences(PdfWriter.PageModeFullScreen);//全屏 writer.setPageEvent(new PdfPageEventHelper() { public void onStartPage(PdfWriter writer, Document document) { writer.setTransition(new PdfTransition(PdfTransition.DISSOLVE, 3)); writer.setDuration(5);//间隔时间 } });
ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(FILE_DIR + "zipPDF.zip")); for (int i = 1; i <= 3; i++) { ZipEntry entry = new ZipEntry("hello_" + i + ".pdf"); zip.putNextEntry(entry); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, zip); writer.setCloseStream(false); document.open(); document.add(new Paragraph("Hello " + i)); document.close(); zip.closeEntry(); } zip.close();
PdfReader reader = new PdfReader(FILE_DIR + "splitPDF.pdf"); /* 拆分一 */ Document dd = new Document(); PdfWriter writer = PdfWriter.getInstance(dd, new FileOutputStream(FILE_DIR + "splitPDF1.pdf")); dd.open(); PdfContentByte cb = writer.getDirectContent(); dd.newPage(); cb.addTemplate(writer.getImportedPage(reader, 1), 0, 0); dd.newPage(); cb.addTemplate(writer.getImportedPage(reader, 2), 0, 0); dd.close(); writer.close(); /* 拆分二 */ Document dd2 = new Document(); PdfWriter writer2 = PdfWriter.getInstance(dd2, new FileOutputStream(FILE_DIR + "splitPDF2.pdf")); dd2.open(); PdfContentByte cb2 = writer2.getDirectContent(); dd2.newPage(); cb2.addTemplate(writer2.getImportedPage(reader, 3), 0, 0); dd2.newPage(); cb2.addTemplate(writer2.getImportedPage(reader, 4), 0, 0); dd2.close(); writer2.close();
PdfReader reader1 = new PdfReader(FILE_DIR + "splitPDF1.pdf"); PdfReader reader2 = new PdfReader(FILE_DIR + "splitPDF2.pdf"); FileOutputStream out = new FileOutputStream(FILE_DIR + "mergePDF.pdf"); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); PdfContentByte cb = writer.getDirectContent(); int totalPages = 0; totalPages += reader1.getNumberOfPages(); totalPages += reader2.getNumberOfPages(); java.util.List<PdfReader> readers = new ArrayList<PdfReader>(); readers.add(reader1); readers.add(reader2); int pageOfCurrentReaderPDF = 0; Iterator<PdfReader> iteratorPDFReader = readers.iterator(); /* Loop through the PDF files and add to the output. */ while (iteratorPDFReader.hasNext()) { PdfReader pdfReader = iteratorPDFReader.next(); /* Create a new page in the target for each source page. */ while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) { document.newPage(); pageOfCurrentReaderPDF++; PdfImportedPage page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); cb.addTemplate(page, 0, 0); } pageOfCurrentReaderPDF = 0; } out.flush(); document.close(); out.close();