iText

编程爱好者联盟 2016-11-06

iText是著名的开放项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。 

官方网站:http://itextpdf.com/

示例版本:itextpdf-5.2.1.jar

生成简单的PDF文件

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(); 

iText

添加多页

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&nbsp;(int&nbsp;i&nbsp;=&nbsp;0;&nbsp;i&nbsp;<&nbsp;10;&nbsp;i++)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;ListItem&nbsp;item&nbsp;=&nbsp;new&nbsp;ListItem(
            String.format("%s:&nbsp;%d&nbsp;movies","country"&nbsp;+&nbsp;(i&nbsp;+&nbsp;1),&nbsp;(i&nbsp;+&nbsp;1)&nbsp;*&nbsp;100),&nbsp;
            new&nbsp;Font(Font.FontFamily.HELVETICA,&nbsp;6,&nbsp;Font.BOLD,&nbsp;BaseColor.WHITE));
&nbsp;&nbsp;&nbsp;&nbsp;List&nbsp;movielist&nbsp;=&nbsp;new&nbsp;List(List.ORDERED,&nbsp;List.ALPHABETICAL);
&nbsp;&nbsp;&nbsp;&nbsp;movielist.setLowercase(List.LOWERCASE);
&nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;(int&nbsp;j&nbsp;=&nbsp;0;&nbsp;j&nbsp;<&nbsp;5;&nbsp;j++)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ListItem&nbsp;movieitem&nbsp;=&nbsp;new&nbsp;ListItem("Title"&nbsp;+&nbsp;(j&nbsp;+&nbsp;1));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;List&nbsp;directorlist&nbsp;=&nbsp;new&nbsp;List(List.UNORDERED);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;(int&nbsp;k&nbsp;=&nbsp;0;&nbsp;k&nbsp;<&nbsp;3;&nbsp;k++)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;directorlist.add(String.format("%s,&nbsp;%s",&nbsp;"Name1"&nbsp;+&nbsp;(k&nbsp;+&nbsp;1),"Name2"&nbsp;+&nbsp;(k&nbsp;+&nbsp;1)));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;movieitem.add(directorlist);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;movielist.add(movieitem);
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;item.add(movielist);
&nbsp;&nbsp;&nbsp;&nbsp;list.add(item);
}
document.add(list);

/* Anchor对象:&nbsp;internal&nbsp;and&nbsp;external&nbsp;links */
document.newPage();
Paragraph&nbsp;country&nbsp;=&nbsp;new&nbsp;Paragraph();
Anchor&nbsp;dest&nbsp;=&nbsp;new&nbsp;Anchor("china",&nbsp;new&nbsp;Font(Font.FontFamily.HELVETICA,&nbsp;14,&nbsp;Font.BOLD,&nbsp;BaseColor.BLUE));
dest.setName("CN");
dest.setReference("http://www.china.com");//external
country.add(dest);
country.add(String.format(":&nbsp;%d&nbsp;sites",&nbsp;10000));
document.add(country);

document.newPage();
Anchor&nbsp;toUS&nbsp;=&nbsp;new&nbsp;Anchor("Go&nbsp;to&nbsp;first&nbsp;page.",&nbsp;new&nbsp;Font(Font.FontFamily.HELVETICA,&nbsp;14,&nbsp;Font.BOLD,&nbsp;BaseColor.BLUE));
toUS.setReference("#CN");//internal
document.add(toUS);

/* Image对象 */
document.newPage();
Image&nbsp;img&nbsp;=&nbsp;Image.getInstance("resource/test.jpg");
img.setAlignment(Image.LEFT&nbsp;|&nbsp;Image.TEXTWRAP);
img.setBorder(Image.BOX);
img.setBorderWidth(10);
img.setBorderColor(BaseColor.WHITE);
img.scaleToFit(1000,&nbsp;72);//大小
img.setRotationDegrees(-30);//旋转
document.add(img);

/* Chapter,&nbsp;Section对象(目录) */
document.newPage();
Paragraph&nbsp;title&nbsp;=&nbsp;new&nbsp;Paragraph("Title");
Chapter&nbsp;chapter&nbsp;=&nbsp;new&nbsp;Chapter(title,&nbsp;1);

title&nbsp;=&nbsp;new&nbsp;Paragraph("Section&nbsp;A");
Section&nbsp;section&nbsp;=&nbsp;chapter.addSection(title);
section.setBookmarkTitle("bmk");
section.setIndentation(30);
section.setBookmarkOpen(false);
section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);

Section&nbsp;subsection&nbsp;=&nbsp;section.addSection(new&nbsp;Paragraph("Sub&nbsp;Section&nbsp;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&nbsp;p&nbsp;=&nbsp;new&nbsp;Paragraph("段落内容");

/* 对齐方式 */
p.setAlignment(Element.ALIGN_JUSTIFIED);

/* 缩进 */
p.setIndentationLeft(1&nbsp;*&nbsp;15f);
p.setIndentationRight((5&nbsp;-&nbsp;1)&nbsp;*&nbsp;15f);

/* 间距 */
p.setSpacingAfter(15f);
p.setSpacingBefore(15f);

管理Page

/* 删除页 */
PdfReader&nbsp;reader&nbsp;=&nbsp;new&nbsp;PdfReader(FILE_DIR&nbsp;+&nbsp;"deletePage.pdf");
reader.selectPages("1,3");
PdfStamper&nbsp;stamp&nbsp;=&nbsp;new&nbsp;PdfStamper(reader,&nbsp;new&nbsp;FileOutputStream(FILE_DIR +&nbsp;"deletePage2.pdf"));
stamp.close();
reader.close();

/* 插入页 */
PdfReader&nbsp;reader&nbsp;=&nbsp;new&nbsp;PdfReader(FILE_DIR&nbsp;+&nbsp;"insertPage.pdf");
PdfStamper&nbsp;stamp&nbsp;=&nbsp;new&nbsp;PdfStamper(reader,&nbsp;new&nbsp;FileOutputStream(FILE_DIR+&nbsp;"insertPage2.pdf"));
stamp.insertPage(2,&nbsp;reader.getPageSize(1));

stamp.close();
reader.close();

/* 页排序 */
PdfWriter&nbsp;writer&nbsp;=&nbsp;PdfWriter.getInstance(doc,&nbsp;out);
writer.setLinearPageMode();

doc.open();
doc.add(new&nbsp;Paragraph("1&nbsp;page"));
doc.newPage();
doc.add(new&nbsp;Paragraph("2&nbsp;page"));
doc.newPage();
doc.add(new&nbsp;Paragraph("3&nbsp;page"));
doc.newPage();
doc.add(new&nbsp;Paragraph("4&nbsp;page"));
doc.newPage();
doc.add(new&nbsp;Paragraph("5&nbsp;page"));

int[]&nbsp;order&nbsp;=&nbsp;{4,3,2,1};
writer.reorderPages(order);

目录大纲

/* 添加一些Page */
document.newPage();
document.add(new&nbsp;Chunk("Chapter&nbsp;1").setLocalDestination("1"));

document.newPage();
document.add(new&nbsp;Chunk("Chapter&nbsp;2").setLocalDestination("2"));
document.add(new&nbsp;Paragraph(new&nbsp;Chunk("Sub&nbsp;2.1").setLocalDestination("2.1")));
document.add(new&nbsp;Paragraph(new&nbsp;Chunk("Sub&nbsp;2.2").setLocalDestination("2.2")));

document.newPage();
document.add(new&nbsp;Chunk("Chapter&nbsp;3").setLocalDestination("3"));

/* 生成大纲 */
PdfContentByte&nbsp;cb&nbsp;=&nbsp;writer.getDirectContent();
PdfOutline&nbsp;root&nbsp;=&nbsp;cb.getRootOutline();

PdfOutline&nbsp;oline1&nbsp;=&nbsp;new&nbsp;PdfOutline(root,&nbsp;PdfAction.gotoLocalPage("1",&nbsp;false),&nbsp;"Chapter&nbsp;1");
PdfOutline&nbsp;oline2&nbsp;=&nbsp;new&nbsp;PdfOutline(root,&nbsp;PdfAction.gotoLocalPage("2",&nbsp;false),&nbsp;"Chapter&nbsp;2");
PdfOutline&nbsp;oline2_1&nbsp;=&nbsp;new&nbsp;PdfOutline(oline2,&nbsp;PdfAction.gotoLocalPage("2.1",&nbsp;false),&nbsp;"Sub&nbsp;2.1");
PdfOutline&nbsp;oline2_2&nbsp;=&nbsp;new&nbsp;PdfOutline(oline2,&nbsp;PdfAction.gotoLocalPage("2.2",&nbsp;false),&nbsp;"Sub&nbsp;2.2");
PdfOutline&nbsp;oline3&nbsp;=&nbsp;new&nbsp;PdfOutline(root,&nbsp;PdfAction.gotoLocalPage("3",&nbsp;false),&nbsp;"Chapter&nbsp;3");

页眉页脚

PdfWriter&nbsp;writer&nbsp;=&nbsp;PdfWriter.getInstance(doc,&nbsp;new&nbsp;FileOutputStream(FILE_DIR&nbsp;+&nbsp;"setHeaderFooter.pdf"));
writer.setPageEvent(new&nbsp;PdfPageEventHelper()&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;void&nbsp;onEndPage(PdfWriter&nbsp;writer,&nbsp;Document&nbsp;document)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PdfContentByte&nbsp;cb&nbsp;=&nbsp;writer.getDirectContent();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cb.saveState();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cb.beginText();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;BaseFont&nbsp;bf&nbsp;=&nbsp;null;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;bf&nbsp;=&nbsp;BaseFont.createFont(BaseFont.HELVETICA,&nbsp;BaseFont.WINANSI,&nbsp;BaseFont.EMBEDDED);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;catch&nbsp;(Exception&nbsp;e)&nbsp;{}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cb.setFontAndSize(bf,&nbsp;10);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;/* Header,分左中右 */
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;float&nbsp;x&nbsp;=&nbsp;document.top(-20);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cb.showTextAligned(PdfContentByte.ALIGN_LEFT,"H-Left",document.left(),&nbsp;x,&nbsp;0);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;writer.getPageNumber()+&nbsp;"&nbsp;page",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(document.right()&nbsp;+&nbsp;document.left())/2,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;x,&nbsp;0);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cb.showTextAligned(PdfContentByte.ALIGN_RIGHT,"H-Right",document.right(),&nbsp;x,&nbsp;0);

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;/* Footer,分左中右 */
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;float&nbsp;y&nbsp;=&nbsp;document.bottom(-20);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cb.showTextAligned(PdfContentByte.ALIGN_LEFT,"F-Left",document.left(),&nbsp;y,&nbsp;0);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;writer.getPageNumber()+"&nbsp;page",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(document.right()&nbsp;+&nbsp;document.left())/2,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;y,&nbsp;0);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cb.showTextAligned(PdfContentByte.ALIGN_RIGHT,"F-Right",document.right(),&nbsp;y,&nbsp;0);

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cb.endText();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cb.restoreState();
&nbsp;&nbsp;&nbsp;&nbsp;}
});

 

幻灯片放映

PdfWriter&nbsp;writer&nbsp;=&nbsp;PdfWriter.getInstance(doc,&nbsp;out);
writer.setPdfVersion(PdfWriter.VERSION_1_5);
writer.setViewerPreferences(PdfWriter.PageModeFullScreen);//全屏
writer.setPageEvent(new&nbsp;PdfPageEventHelper()&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;void&nbsp;onStartPage(PdfWriter&nbsp;writer,&nbsp;Document&nbsp;document)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;writer.setTransition(new&nbsp;PdfTransition(PdfTransition.DISSOLVE,&nbsp;3));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;writer.setDuration(5);//间隔时间
&nbsp;&nbsp;&nbsp;&nbsp;}
});

压缩为Zip

ZipOutputStream&nbsp;zip&nbsp;=&nbsp;new&nbsp;ZipOutputStream(new&nbsp;FileOutputStream(FILE_DIR&nbsp;+&nbsp;"zipPDF.zip"));
for&nbsp;(int&nbsp;i&nbsp;=&nbsp;1;&nbsp;i&nbsp;<=&nbsp;3;&nbsp;i++)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;ZipEntry&nbsp;entry&nbsp;=&nbsp;new&nbsp;ZipEntry("hello_"&nbsp;+&nbsp;i&nbsp;+&nbsp;".pdf");
&nbsp;&nbsp;&nbsp;&nbsp;zip.putNextEntry(entry);
&nbsp;&nbsp;&nbsp;&nbsp;Document&nbsp;document&nbsp;=&nbsp;new&nbsp;Document();
&nbsp;&nbsp;&nbsp;&nbsp;PdfWriter&nbsp;writer&nbsp;=&nbsp;PdfWriter.getInstance(document,&nbsp;zip);
&nbsp;&nbsp;&nbsp;&nbsp;writer.setCloseStream(false);
&nbsp;&nbsp;&nbsp;&nbsp;document.open();
&nbsp;&nbsp;&nbsp;&nbsp;document.add(new&nbsp;Paragraph("Hello&nbsp;"&nbsp;+&nbsp;i));
 &nbsp;&nbsp;&nbsp;&nbsp;document.close();
 &nbsp;&nbsp;&nbsp;&nbsp;zip.closeEntry();
 }
 zip.close();

分割PDF

PdfReader&nbsp;reader&nbsp;=&nbsp;new&nbsp;PdfReader(FILE_DIR&nbsp;+&nbsp;"splitPDF.pdf");

/* 拆分一 */
Document&nbsp;dd&nbsp;=&nbsp;new&nbsp;Document();
PdfWriter&nbsp;writer&nbsp;=&nbsp;PdfWriter.getInstance(dd,&nbsp;new&nbsp;FileOutputStream(FILE_DIR&nbsp;+&nbsp;"splitPDF1.pdf"));
dd.open();
PdfContentByte&nbsp;cb&nbsp;=&nbsp;writer.getDirectContent();
dd.newPage();
cb.addTemplate(writer.getImportedPage(reader,&nbsp;1),&nbsp;0,&nbsp;0);
dd.newPage();
cb.addTemplate(writer.getImportedPage(reader,&nbsp;2),&nbsp;0,&nbsp;0);
dd.close();
writer.close();

/* 拆分二 */
Document&nbsp;dd2&nbsp;=&nbsp;new&nbsp;Document();
PdfWriter&nbsp;writer2&nbsp;=&nbsp;PdfWriter.getInstance(dd2,&nbsp;new&nbsp;FileOutputStream(FILE_DIR&nbsp;+&nbsp;"splitPDF2.pdf"));
dd2.open();
PdfContentByte&nbsp;cb2&nbsp;=&nbsp;writer2.getDirectContent();
dd2.newPage();
cb2.addTemplate(writer2.getImportedPage(reader,&nbsp;3),&nbsp;0,&nbsp;0);
dd2.newPage();
cb2.addTemplate(writer2.getImportedPage(reader,&nbsp;4),&nbsp;0,&nbsp;0);
dd2.close();
writer2.close();

合并PDF

PdfReader&nbsp;reader1&nbsp;=&nbsp;new&nbsp;PdfReader(FILE_DIR&nbsp;+&nbsp;"splitPDF1.pdf");
PdfReader&nbsp;reader2&nbsp;=&nbsp;new&nbsp;PdfReader(FILE_DIR&nbsp;+&nbsp;"splitPDF2.pdf");

FileOutputStream&nbsp;out&nbsp;=&nbsp;new&nbsp;FileOutputStream(FILE_DIR&nbsp;+&nbsp;"mergePDF.pdf");

Document&nbsp;document&nbsp;=&nbsp;new&nbsp;Document();
PdfWriter&nbsp;writer&nbsp;=&nbsp;PdfWriter.getInstance(document,&nbsp;out);

document.open();
PdfContentByte&nbsp;cb&nbsp;=&nbsp;writer.getDirectContent();

int&nbsp;totalPages&nbsp;=&nbsp;0;
totalPages&nbsp;+=&nbsp;reader1.getNumberOfPages();
totalPages&nbsp;+=&nbsp;reader2.getNumberOfPages();

java.util.List<PdfReader>&nbsp;readers&nbsp;=&nbsp;new&nbsp;ArrayList<PdfReader>();
readers.add(reader1);
readers.add(reader2);

int&nbsp;pageOfCurrentReaderPDF&nbsp;=&nbsp;0;
Iterator<PdfReader>&nbsp;iteratorPDFReader&nbsp;=&nbsp;readers.iterator();

/*&nbsp;Loop&nbsp;through&nbsp;the&nbsp;PDF&nbsp;files&nbsp;and&nbsp;add&nbsp;to&nbsp;the&nbsp;output. */
while&nbsp;(iteratorPDFReader.hasNext())&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;PdfReader&nbsp;pdfReader&nbsp;=&nbsp;iteratorPDFReader.next();

&nbsp;&nbsp;&nbsp;&nbsp;/*&nbsp;Create&nbsp;a&nbsp;new&nbsp;page&nbsp;in&nbsp;the&nbsp;target&nbsp;for&nbsp;each&nbsp;source&nbsp;page. */
&nbsp;&nbsp;&nbsp;&nbsp;while&nbsp;(pageOfCurrentReaderPDF&nbsp;<&nbsp;pdfReader.getNumberOfPages())&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;document.newPage();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pageOfCurrentReaderPDF++;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PdfImportedPage&nbsp;page&nbsp;=&nbsp;writer.getImportedPage(pdfReader,&nbsp;pageOfCurrentReaderPDF);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cb.addTemplate(page,&nbsp;0,&nbsp;0);
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;pageOfCurrentReaderPDF&nbsp;=&nbsp;0;
}
out.flush();
document.close();
out.close();

相关推荐