美文网首页
Java生成PDF文件

Java生成PDF文件

作者: Wpixel | 来源:发表于2019-01-29 15:11 被阅读0次

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

    提供自己的一些工具类

    生成PDF文件所需的jar包

    1、创建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----");
        }
        
        //创建一个最基本的 pdf
        public static void fillTemplate(String outpath) {
            try {
                //1 创建Document
                Document document = new Document();
                //2 获取PdfWriter
                PdfWriter.getInstance(document, new FileOutputStream(outpath));
                //3 打开
                document.open();
                //4 添加内容
                document.add(new Paragraph("Hello World"));
                //5 关闭
                document.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    2、进阶

    创建一个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 {
                /**
                 * 设置字体
                 * 
                 * 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;
        }
    }
    

    创建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=============");
        }
        
        /**
         * 创建一个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);//文档竖方向
            //如果没有则创建
            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, "合作协议"));
            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, "《根据中华人民共和国合同法》的有关规定,经甲、乙双方友好协商,本着长期平等合作.....吧啦吧啦吧啦吧啦吧啦吧啦吧啦吧啦");
            doc.add(text05);
            
            //一、合作方式及条件
            doc.add(PdfFontUtils.getFont(2, "一、合作方式及条件"));
            doc.add(PdfFontUtils.getFont(5, "1.双方根据国家法律规定建立合作关系,双方严格遵守和执行国家各项方针政策和有关法律、法规和条例规定。 "));
            doc.add(PdfFontUtils.getFont(5, "2.双方严格按照《中华人民共和国招标投标法》及相关规定实施合作。 "));
            doc.add(PdfFontUtils.getFont(5, "3.双方本着密切配合、分工协作、保证质量、按期完成的原则,共同做好工作。 "));
            
            //二、权利义务
            doc.add(PdfFontUtils.getFont(2, "二、权利义务"));
            doc.add(PdfFontUtils.getFont(5, "1.双方根据国家法律规定建立合作关系,双方严格遵守和执行国家各项方针政策和有关法律、法规和条例规定。 "));
            doc.add(PdfFontUtils.getFont(5, "2.双方严格按照《中华人民共和国招标投标法》及相关规定实施合作。 "));
            doc.add(PdfFontUtils.getFont(5, "3.双方本着密切配合、分工协作、保证质量、按期完成的原则,共同做好工作。 "));
            
            //三、其他
            doc.add(PdfFontUtils.getFont(2, "三、其他"));
            doc.add(PdfFontUtils.getFont(5, "1.双方根据国家法律规定建立合作关系,双方严格遵守和执行国家各项方针政策和有关法律、法规和条例规定。 "));
            doc.add(PdfFontUtils.getFont(5, "2.双方严格按照《中华人民共和国招标投标法》及相关规定实施合作。 "));
            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, "授权代理人:")));
            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.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 有问题回复


    作者是一名自由程序员,住在上海,喜欢音乐、小说、旅行、以及编程。

    P.S. 如果您喜欢这篇文章并且希望学习编程技术的话,请关注一下

    相关文章

      网友评论

          本文标题:Java生成PDF文件

          本文链接:https://www.haomeiwen.com/subject/zbaemftx.html