Java生成PDF文件

最近在學C# xaml,好久沒更新了,今天就水一篇吧

提供自己的一些工具類

生成PDF文件所需的jar包

1、創(chuàng)建PDF —— hello word

public class CreatePdfText {
        public static void main(String[] args) {
        System.out.println("---start----");
        try {
            fillTemplate("F:\\test\\fillTemplate.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("---end----");
    }
    
    //創(chuàng)建一個最基本的 pdf
    public static void fillTemplate(String outpath) {
        try {
            //1 創(chuàng)建Document
            Document document = new Document();
            //2 獲取PdfWriter
            PdfWriter.getInstance(document, new FileOutputStream(outpath));
            //3 打開
            document.open();
            //4 添加內(nèi)容
            document.add(new Paragraph("Hello World"));
            //5 關(guān)閉
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2、進階

創(chuàng)建一個PDF字體樣式工具類

package test;

import java.io.IOException;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;

public class PdfFontUtils {

    // 字體
    private static BaseFont baseFont = null;
    
    static{
        try {
            /**
             * 設(shè)置字體
             * 
             * windows路徑字體
             * FONT_TYPE=C:/Windows/fonts/simsun.ttc
             * linux路徑字體 宋體 (如果沒有這個字體文件,就將windows的字體傳上去)
             * FONT_TYPE=/usr/share/fonts/win/simsun.ttc
             */
            //可以用配置文件讀取
            //獲取配置
            //PropertiesLoader pl = new PropertiesLoader("/config/config.properties");  
            //拼接文件web訪問路徑
            //String FONT_TYPE = pl.getProperty("FONT_TYPE");  
            //解決中文問題  幼圓
            baseFont = BaseFont.createFont("C:/Windows/fonts/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
            
    /**
     * 文檔超級  排版
     * @param type 1-標題 2-標題一  3-標題二 4-標題三  5-正文  6-左對齊
     */
    public static Paragraph getFont(int type, String text){
        Font font = new Font(baseFont);
        if(1 == type){//1-標題
            font.setSize(16f);
            font.setStyle(Font.BOLD);
        } else if(2 == type){//2-標題一
            font.setSize(16f);
            font.setStyle(Font.BOLD);
        } else if(3 == type){//3-標題二
            font.setSize(14f);
            font.setStyle(Font.BOLD);
        } else if(4 == type){//4-標題三
            font.setSize(14f);
        } else if(5 == type){//5-正文
            font.setSize(10.5f);
        } else if(6 == type){//6-左對齊
            font.setSize(10.5f);
        } else {
            font.setSize(10.5f);//默認大小
        }
        //注: 字體必須和 文字一起new
        Paragraph paragraph = new Paragraph(text, font);
        if(1 == type){
            paragraph.setAlignment(Paragraph.ALIGN_CENTER);//居中
            paragraph.setSpacingBefore(10f);//上間距
            paragraph.setSpacingAfter(10f);//下間距
        } else if(2 == type){//2-標題一
            paragraph.setAlignment(Element.ALIGN_JUSTIFIED); //默認
            paragraph.setSpacingBefore(2f);//上間距
            paragraph.setSpacingAfter(2f);//下間距
        } else if(3 == type){
            paragraph.setSpacingBefore(2f);//上間距
            paragraph.setSpacingAfter(1f);//下間距
        } else if(4 == type){//4-標題三
            //paragraph.setAlignment(Element.ALIGN_RIGHT);//右對齊 
            paragraph.setSpacingBefore(2f);//上間距
            paragraph.setSpacingAfter(2f);//下間距
        } else if(5 == type){
            paragraph.setAlignment(Element.ALIGN_JUSTIFIED); 
            paragraph.setFirstLineIndent(24);//首行縮進
            paragraph.setSpacingBefore(1f);//上間距
            paragraph.setSpacingAfter(1f);//下間距
        } else if(6 == type){//左對齊
            paragraph.setAlignment(Element.ALIGN_LEFT); 
            paragraph.setSpacingBefore(1f);//上間距
            paragraph.setSpacingAfter(1f);//下間距
        }
        //paragraph.setIndentationLeft(50);//整體縮進左邊
        //paragraph.setFirstLineIndent(40);//首行縮進
        return paragraph;
    }
}

創(chuàng)建pdf文件

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class CreatePdfText {
    
    public static void main(String[] args) {
        System.out.println("===========start=============");
        try {
            Document doc = createPdf("F:\\test\\test.pdf");
            //生成  合同文件
            createFile(doc);
            doc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("===========end=============");
    }
    
    /**
     * 創(chuàng)建一個pdf并打開
     * @param outpath  pdf路徑
     */
    public static Document createPdf(String outpath) throws DocumentException, IOException{
        //頁面大小
        //Rectangle rect = new Rectangle(PageSize.A4.rotate());//文檔橫方向
        Rectangle rect = new Rectangle(PageSize.A4);//文檔豎方向
        //如果沒有則創(chuàng)建
        File saveDir = new File(outpath);
        File dir = saveDir.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }
        Document doc = new Document(rect);
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(outpath));
        //PDF版本(默認1.4)
        writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);
        //文檔屬性
        doc.addTitle("Title@wpixel");
        doc.addAuthor("Author@wpixel");
        doc.addSubject("Subject@wpixel");
        doc.addKeywords("Keywords@wpixel");
        doc.addCreator("Creator@wpixel");
        //頁邊空白
        doc.setMargins(40, 40, 40, 40);
        //打開文檔
        doc.open();
        return doc;
    }
    
    public static void createFile(Document doc) throws DocumentException{
        doc.add(PdfFontUtils.getFont(1, "合作協(xié)議"));
        doc.add(PdfFontUtils.getFont(6, "甲方:"));
        doc.add(PdfFontUtils.getFont(6, "乙方:"));
        doc.add(PdfFontUtils.getFont(6, "時間:"));
        doc.add(PdfFontUtils.getFont(6, "地點:"));
        Paragraph text05 = PdfFontUtils.getFont(5, "《根據(jù)中華人民共和國合同法》的有關(guān)規(guī)定,經(jīng)甲、乙雙方友好協(xié)商,本著長期平等合作.....吧啦吧啦吧啦吧啦吧啦吧啦吧啦吧啦");
        doc.add(text05);
        
        //一、合作方式及條件
        doc.add(PdfFontUtils.getFont(2, "一、合作方式及條件"));
        doc.add(PdfFontUtils.getFont(5, "1.雙方根據(jù)國家法律規(guī)定建立合作關(guān)系,雙方嚴格遵守和執(zhí)行國家各項方針政策和有關(guān)法律、法規(guī)和條例規(guī)定。 "));
        doc.add(PdfFontUtils.getFont(5, "2.雙方嚴格按照《中華人民共和國招標投標法》及相關(guān)規(guī)定實施合作。 "));
        doc.add(PdfFontUtils.getFont(5, "3.雙方本著密切配合、分工協(xié)作、保證質(zhì)量、按期完成的原則,共同做好工作。 "));
        
        //二、權(quán)利義務(wù)
        doc.add(PdfFontUtils.getFont(2, "二、權(quán)利義務(wù)"));
        doc.add(PdfFontUtils.getFont(5, "1.雙方根據(jù)國家法律規(guī)定建立合作關(guān)系,雙方嚴格遵守和執(zhí)行國家各項方針政策和有關(guān)法律、法規(guī)和條例規(guī)定。 "));
        doc.add(PdfFontUtils.getFont(5, "2.雙方嚴格按照《中華人民共和國招標投標法》及相關(guān)規(guī)定實施合作。 "));
        doc.add(PdfFontUtils.getFont(5, "3.雙方本著密切配合、分工協(xié)作、保證質(zhì)量、按期完成的原則,共同做好工作。 "));
        
        //三、其他
        doc.add(PdfFontUtils.getFont(2, "三、其他"));
        doc.add(PdfFontUtils.getFont(5, "1.雙方根據(jù)國家法律規(guī)定建立合作關(guān)系,雙方嚴格遵守和執(zhí)行國家各項方針政策和有關(guān)法律、法規(guī)和條例規(guī)定。 "));
        doc.add(PdfFontUtils.getFont(5, "2.雙方嚴格按照《中華人民共和國招標投標法》及相關(guān)規(guī)定實施合作。 "));
        doc.add(PdfFontUtils.getFont(5, "3.自定義 "));
        
        PdfPTable table = new PdfPTable(2);
        table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
        PdfPCell cell;
        cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "甲方:(蓋章)")));
        cell.setColspan(1);
        cell.setBorder(0);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "乙方:(蓋章)")));
        cell.setColspan(1);
        cell.setBorder(0);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "法定代表人或負責人簽章")));
        cell.setColspan(1);
        cell.setBorder(0);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "法定代表人或負責人簽章")));
        cell.setColspan(1);
        cell.setBorder(0);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "地址:")));
        cell.setColspan(1);
        cell.setBorder(0);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "地址:")));
        cell.setColspan(1);
        cell.setBorder(0);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "開戶銀行:")));
        cell.setColspan(1);
        cell.setBorder(0);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "開戶銀行:")));
        cell.setColspan(1);
        cell.setBorder(0);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "郵編:")));
        cell.setColspan(1);
        cell.setBorder(0);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "郵編:")));
        cell.setColspan(1);
        cell.setBorder(0);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "授權(quán)代理人:")));
        cell.setColspan(1);
        cell.setBorder(0);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "項目經(jīng)理:")));
        cell.setColspan(1);
        cell.setBorder(0);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "電話:")));
        cell.setColspan(1);
        cell.setBorder(0);
        table.addCell(cell);
        cell.setBorder(Rectangle.NO_BORDER);
        cell = new PdfPCell(new Phrase(PdfFontUtils.getFont(5, "電話:")));
        cell.setColspan(1);
        cell.setBorder(0);
        table.addCell(cell);
        doc.add(table);
    }
    
}

o( ̄︶ ̄)o 有問題回復(fù)


作者是一名自由程序員,住在上海,喜歡音樂、小說、旅行、以及編程。

P.S. 如果您喜歡這篇文章并且希望學習編程技術(shù)的話,請關(guān)注一下

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容