itext生成pdf,批量壓縮檔案
阿新 • • 發佈:2019-02-15
最近使用itext生成pdf,並涉及批量壓縮檔案
maven的pom.xml檔案中引入itext檔案
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.2.0</version>
</dependency>
//以下例子設計pdf生成,新增表、文字,圖片,另有Chapter,Section等可以上網搜尋。。。
public class ItextPdf{
public static void main(String[] args){
Document document = new Document(PageSize.LEGAL);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld"+(new Date()).getTime()+".pdf")); // 所有整合自 OutputStream的out
Rectangle rect = new Rectangle(36, 54, 648, 954);
rect.setBorderColor(BaseColor.BLACK);
writer.setBoxSize("art", rect);
PDFPageFooter footer = new PDFPageFooter();//新增頁尾
writer.setPageEvent(footer);
document.open();
//預設字型
BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
Font mainFont = new Font(bfChinese, 9);// 小五
//加在微軟雅黑字型檔案庫,使用“微軟雅黑”字型
BaseFont bfChinese = BaseFont.createFont(OrderPDFUtil.class.getResource("/font/msyh.ttf").getFile(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font msyhFont = new Font(bfChinese, size);
PdfPTable table = new PdfPTable(3);//2列的表格
//以下2種表或列寬的匹配方式有可能互斥
//寬度100% 隨機匹配列寬
table.setWidthPercentage(100);
//設定列寬,鎖定列寬
table.setWidths(new int[] { 350, 139, 50 });
table.setTotalWidth(540);
table.setLockedWidth(true);
//設定跨頁面自動分割表格
table.setSplitLate(false);// 表示單元格是否跨頁顯示
table.setSplitRows(true);// 表示行是否跨頁顯示
// 設定單元格的預設屬性
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);//水平居左
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
table.getDefaultCell().setFixedHeight(CELLHIGHT);//固定高度
table.getDefaultCell().setMinimumHeight(CELLHIGHT);//最小高度
table.getDefaultCell().setBackgroundColor(new BaseColor(0, 0, 0)); //背景顏色
table.getDefaultCell().setBorderColor(new BaseColor(250, 250, 250));//邊框顏色
table.getDefaultCell().setPadding(5);//邊距間隔
table.getDefaultCell().setBorderWidth(0);//邊框寬度
//以下文字輸出"Paragraph1 \n Paragraph2 Phrase1"
Paragraph paragraph = new Paragraph("Paragraph1 ", mainFont);
paragraph.add(new Paragraph(" Paragraph2", msyhFont));//換行
paragraph.add(new Phrase(" Phrase1", msyhFont));//不換行
PdfPCell cell = new PdfPCell(paragraph);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);// 設定內容水平居中顯示
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setColspan(3);//佔據3列
cell.setBorderColor(new BaseColor(0, 0, 0));
document.add(table);
document.close;
}
}
//頁尾,繼承PdfPageEventHelper重寫onEndPage方法,結果為右下角輸出頁碼1/3字樣
public class PDFPageFooter extends PdfPageEventHelper {
String header;
PdfTemplate total;
public void setHeader(String header) {
this.header = header;
}
public void onOpenDocument(PdfWriter writer, Document document) {
total = writer.getDirectContent().createTemplate(30, 16);
}
public void onEndPage(PdfWriter writer, Document document) {
PdfPTable table = new PdfPTable(3);
try {
table.setWidths(new int[] { 24, 24, 2 });
table.setTotalWidth(527);
table.setLockedWidth(true);
table.getDefaultCell().setFixedHeight(20);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table.addCell(header);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(String.format(" %d /", writer.getPageNumber()));
PdfPCell cell = new PdfPCell(Image.getInstance(total));
cell.setBorder(Rectangle.NO_BORDER);
table.addCell(cell);
table.writeSelectedRows(0, -1, 34, 16, writer.getDirectContent());
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
public void onCloseDocument(PdfWriter writer, Document document) {
ColumnText.showTextAligned(total, Element.ALIGN_LEFT, new Phrase(String.valueOf(writer.getPageNumber() - 1)), 2, 2, 0);
}
}
壓縮檔案:
ZipOutputStream zipOutput = new ZipOutputStream(response.getOutputStream());
if (CollectionUtils.isNotEmpty(objects)) {
for (Object object : objects) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
String pdfName = "xxx.pdf"
Document document = new Document(PageSize.LEGAL);
PdfWriter writer = PdfWriter.getInstance(document, outputStream)
......
document.close();
//以下2句位置不可調換,必須是"GBK"否則亂碼
zipOutput.setEncoding("GBK");
zipOutput.putNextEntry(new ZipEntry(pdfName));
zipOutput.write(outputStream.toByteArray());
}
}
zipOutput.close();
maven的pom.xml檔案中引入itext檔案
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.2.0</version>
</dependency>
//以下例子設計pdf生成,新增表、文字,圖片,另有Chapter,Section等可以上網搜尋。。。
public class ItextPdf{
public static void main(String[] args){
Document document = new Document(PageSize.LEGAL);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld"+(new Date()).getTime()+".pdf")); // 所有整合自 OutputStream的out
Rectangle rect = new Rectangle(36, 54, 648, 954);
rect.setBorderColor(BaseColor.BLACK);
writer.setBoxSize("art", rect);
PDFPageFooter footer = new PDFPageFooter();//新增頁尾
writer.setPageEvent(footer);
document.open();
//預設字型
BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
Font mainFont = new Font(bfChinese, 9);// 小五
//加在微軟雅黑字型檔案庫,使用“微軟雅黑”字型
BaseFont bfChinese = BaseFont.createFont(OrderPDFUtil.class.getResource("/font/msyh.ttf").getFile(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font msyhFont = new Font(bfChinese, size);
PdfPTable table = new PdfPTable(3);//2列的表格
//以下2種表或列寬的匹配方式有可能互斥
//寬度100% 隨機匹配列寬
table.setWidthPercentage(100);
//設定列寬,鎖定列寬
table.setWidths(new int[] { 350, 139, 50 });
table.setTotalWidth(540);
table.setLockedWidth(true);
//設定跨頁面自動分割表格
table.setSplitLate(false);// 表示單元格是否跨頁顯示
table.setSplitRows(true);// 表示行是否跨頁顯示
// 設定單元格的預設屬性
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);//水平居左
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
table.getDefaultCell().setFixedHeight(CELLHIGHT);//固定高度
table.getDefaultCell().setMinimumHeight(CELLHIGHT);//最小高度
table.getDefaultCell().setBackgroundColor(new BaseColor(0, 0, 0)); //背景顏色
table.getDefaultCell().setBorderColor(new BaseColor(250, 250, 250));//邊框顏色
table.getDefaultCell().setPadding(5);//邊距間隔
table.getDefaultCell().setBorderWidth(0);//邊框寬度
//以下文字輸出"Paragraph1 \n Paragraph2 Phrase1"
Paragraph paragraph = new Paragraph("Paragraph1 ", mainFont);
paragraph.add(new Paragraph(" Paragraph2", msyhFont));//換行
paragraph.add(new Phrase(" Phrase1", msyhFont));//不換行
PdfPCell cell = new PdfPCell(paragraph);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);// 設定內容水平居中顯示
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setColspan(3);//佔據3列
cell.setBorderColor(new BaseColor(0, 0, 0));
document.add(table);
document.close;
}
}
//頁尾,繼承PdfPageEventHelper重寫onEndPage方法,結果為右下角輸出頁碼1/3字樣
public class PDFPageFooter extends PdfPageEventHelper {
String header;
PdfTemplate total;
public void setHeader(String header) {
this.header = header;
}
public void onOpenDocument(PdfWriter writer, Document document) {
total = writer.getDirectContent().createTemplate(30, 16);
}
public void onEndPage(PdfWriter writer, Document document) {
PdfPTable table = new PdfPTable(3);
try {
table.setWidths(new int[] { 24, 24, 2 });
table.setTotalWidth(527);
table.setLockedWidth(true);
table.getDefaultCell().setFixedHeight(20);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table.addCell(header);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(String.format(" %d /", writer.getPageNumber()));
PdfPCell cell = new PdfPCell(Image.getInstance(total));
cell.setBorder(Rectangle.NO_BORDER);
table.addCell(cell);
table.writeSelectedRows(0, -1, 34, 16, writer.getDirectContent());
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
public void onCloseDocument(PdfWriter writer, Document document) {
ColumnText.showTextAligned(total, Element.ALIGN_LEFT, new Phrase(String.valueOf(writer.getPageNumber() - 1)), 2, 2, 0);
}
}
壓縮檔案:
ZipOutputStream zipOutput = new ZipOutputStream(response.getOutputStream());
if (CollectionUtils.isNotEmpty(objects)) {
for (Object object : objects) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
String pdfName = "xxx.pdf"
Document document = new Document(PageSize.LEGAL);
PdfWriter writer = PdfWriter.getInstance(document, outputStream)
......
document.close();
//以下2句位置不可調換,必須是"GBK"否則亂碼
zipOutput.setEncoding("GBK");
zipOutput.putNextEntry(new ZipEntry(pdfName));
zipOutput.write(outputStream.toByteArray());
}
}
zipOutput.close();
定位:
1、單純 text定位:
PdfContentByte cb = writer.DirectContent;
cb.BeginText();
BaseFont bfont = BaseFont.CreateFont(
@"c:\windows\fonts\SIMHEI.TTF"
, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//設定字型:黑體
cb.SetFontAndSize(bfont, 18);
//設定字號
cb.SetCharacterSpacing(1);
//設定字間距
cb.SetRGBColorFill(66, 00, 00);
//設定文字顏色
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT,
"在位置100,70處開始顯示文字"
, 100, 70,0);
cb.EndText();
2、table定位
table
.writeSelectedRows(0, -1, 36, 600, writer.getDirectContent());