iText

来源:http://www.cnblogs.com/wangyonghao/archive/2016/11/05/6033871.html
-Advertisement-
Play Games

iText是著名的開放項目,是用於生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉化為PDF文件。 官方網站:http://itextpdf.com/ 示例版本:itextpdf-5.2.1.jar 示例代碼 document.add ...


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"));
添加多個Page
PdfReader reader = new PdfReader(FILE_DIR + "deletePage.pdf");

/* 刪除Page */
reader.selectPages("1,3");
PdfStamper stamp new PdfStamper(reader, new FileOutputStream(FILE_DIR + "deletePage2.pdf"));

/* 插入Page */
stamp.insertPage(2, reader.getPageSize(1));  

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

/* 排序Page */
PdfWriter writer = PdfWriter.getInstance(doc, out);  
writer.setLinearPageMode(); 
writer.reorderPages({4,3,2,1});  
Page刪除、插入、排序
/* 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);
添加內容
Paragraph p = new Paragraph("段落內容");

/* 對齊方式 */
p.setAlignment(Element.ALIGN_JUSTIFIED);

/* 縮進 */
p.setIndentationLeft(1 * 15f);
p.setIndentationRight((5 - 1) * 15f);

/* 間距 */
p.setSpacingAfter(15f);
p.setSpacingBefore(15f);
段落設置
PdfPTable table = new PdfPTable(3);
PdfPCell cell;
cell new PdfPCell(new Phrase("Cell with colspan 3"));
cell.setColspan(3);
table.addCell(cell);

cell new PdfPCell(new Phrase("Cell with rowspan 2"));
cell.setRowspan(2);
table.addCell(cell);

table.addCell("row 1; cell 1");
table.addCell("row 1; cell 2");
table.addCell("row 2; cell 1");
table.addCell("row 2; cell 2");

document.add(table);
表格
PdfPTable table = new PdfPTable(4);

/* 1行2列 */
PdfPTable nested1 new PdfPTable(2);
nested1.addCell("1.1");
nested1.addCell("1.2");

/* 2行1列 */
PdfPTable nested2 new PdfPTable(1);
nested2.addCell("2.1");
nested2.addCell("2.2");

/* 將表格插入到指定位置 */
table.addCell(nested1);
table.addCell(nested2);

document.add(table);
表格嵌套
PdfPTable table = new PdfPTable(widths);

/* 百分比寬度 */
table.setWidthPercentage(50);
table.setHorizontalAlignment(Element.ALIGN_RIGHT); //對齊方式

/* 固定寬度 */
table.setTotalWidth(300);
table.setLockedWidth(true);

/* 上下間距 */
table.setSpacingBefore(15f);
table.setSpacingAfter(15f);

/* 百分比列寬 */
float[] widths = {40f, 40f, 20f, 80f};
table.setWidths(widths);

/* 固定列寬 */
Rectangle r new Rectangle(PageSize.A4.getRight(72), PageSize.A4.getTop(72));
table.setWidthPercentage(widths, r);
表格設置
PdfPTable datatable = new PdfPTable(5);
datatable.setWidths({ 9, 4, 8, 10, 8 });// percentage

datatable.addCell("Clock #");
datatable.addCell("Trans Type");
datatable.addCell("Cusip");
datatable.addCell("Long Name");
datatable.addCell("Quantity");

datatable.setHeaderRows(1);
表格標題行
PdfPCell cell = new PdfPCell(new Paragraph("blah blah"));
cell.setNoWrap(false); //自動換行
cell.setFixedHeight(50f); //固定高度
cell.setMinimumHeight(50f); //最小高度
cell.setUseBorderPadding(true); //內填充
cell.setPadding(10f); // 內填充統一
cell.setPaddingTop(0f); //內填充上
cell.setPaddingLeft(20f);//內填充左
cell.setBorder(Rectangle.BOTTOM); //邊框
cell.setBorderColorBottom(BaseColor.MAGENTA); //邊框顏色
cell.setBorderWidthBottom(5f); //邊框寬度
cell.setBackgroundColor(BaseColor.RED); //背景
cell.setGrayFill(0.25f);//背景灰色度

table.setExtendLastRow(true); //最後一行拉長到page底部
cell = new PdfPCell(new Paragraph("page footer",fontZH));

cell = table1.getDefaultCell(); // 預設單元格,提供預設設置
單元格設置 水印背景
/* 左右箭頭 */
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);
畫圖
/* 添加一些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);//間隔時間
    }
});
幻燈片放映 條形碼
/* 實現FontProvider介面比如叫MyFontProvider,在getFont()方法里設置你的字體庫 */
HashMap providers = new HashMap();
providers.put(HTMLWorker.FONT_PROVIDER, new MyFontProvider());
List<Element> list = HTMLWorker.parseToList(new StringReader(html),new StyleSheet(),providers);
for (Element e : list) {
    document.add(e);
}
自定義字體
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();
拆分PDF 合併PDF
Document document = new Document(PageSize.LETTER);
PdfWriter.getInstance(document, new FileOutputStream("c://testpdf1.pdf"));
document.open();
HTMLWorker htmlWorker = new HTMLWorker(document);
htmlWorker.parse(new StringReader("<h1>This is a test!</h1>"));
document.close();
HTML轉換為PDF
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();
壓縮為ZIP

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 原文件(數據已經脫敏): ...
  • 舉例 我們先從示例應用程式的一些摘錄開始。下麵是暴露Person對象的響應信息庫。很類似於傳統的,非響應信息庫,只不過它返回Flux<Person>而傳統的返回List<Person>,以及返回Mono<Person>的地方返回Person。Mono<Void>用作完成標識:指出何時保存被完成。關於 ...
  • 今天我們一起來學習WebService。它到底是幹啥用的? Web service是一個平臺獨立的,低耦合的,自包含的、基於可編程的web的應用程式,可使用開放的XML(標準通用標記語言下的一個子集)標準來描述、發佈、發現、協調和配置這些應用程式,用於開發分散式的互操作的應用程式。 一:Web Se ...
  • |定義|含義| | | | |int i|定義整形變數i| |int p|p為指向整形數據類型的指針變數| |int a[n]|定義有n個元素的整型數組a| |int p[n]|定義由n個指向整型數據的指針元素組成的指針數組p| |int ( p)[n]|p為指向n個元素的一維數組的指針變數| |i ...
  • php的閉包可能不常用,但是在某些場合之下還是可以考慮用php的閉包來實現某些功能的,比如遞歸,這裡講一下用php的閉包實現遞歸 這是一個簡單的使用php閉包實現遞歸的函數,其實,假如我們對這個函數稍微修改一下,是可以實現很多功能的,比如說,無限極分類。 關於裡面的閉包函數,其實,我們也可以不用引用 ...
  • List Set 都是介面,都繼承了Collection介面 ArrayList LinkList 直接實現了List介面 HashSet 實現了Set介面 HashSet 實現了Set介面 TreeSet繼承父類AbstractSet 間接的實現了Set 介面 Map 是介面,沒有實現Collec ...
  • JMS是一個用於提供消息服務的技術規範,它制定了在整個消息服務提供過程中的所有數據結構和交互流程。 而activemq則是消息隊列服務,是面向消息中間件(MOM)的最終實現,是真正的服務提供者。 jms 的一個標準或者說是一個協議。 通常用於企業級應用的消息傳遞。 主要有topic 消息(1 對多) ...
  • 一、前言 在之前的隨筆之中,我們已經瞭解Java通過上傳組件來實現上傳和下載,這次我們來瞭解Struts2的上傳和下載。 註意:文件上傳時,我們需要將表單提交方式設置為"POST"方式,並且將enctype屬性設置為"multipart/form-data",該屬性的預設值為"application ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...