zoukankan      html  css  js  c++  java
  • dom4j实现用已有的PDF模板+xml,生成新的PDF

    应用场景

    在已经有了PDF模板,只需要我们动态填充一下数据的情况下,例如PDF报表,发票等

    需要的jar包

     还要准备一个PDF模板,和xml

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <FormDefine xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    	<Config>
    	
    	  <Filed name="Name" >
    			<Page>1</Page>
    			<X>78</X>
    			<Y>650</Y>
    			<Font>楷体gb2312</Font>
    			<Size>20</Size>
    			
    		</Filed>
    		
    		<Filed name="Bank" >
    			<Page>1</Page>
    			<X>245</X>
    			<Y>650</Y>
    			<Font>楷体gb2312</Font>
    			<Size>20</Size>
    		
    		</Filed>
    		
    		<Filed name="CityName">
    			<Page>1</Page>
    			<X>445</X>
    			<Y>650</Y>
    			<Font>楷体gb2312</Font>
    			<Size>20</Size>
    		</Filed>
    	</Config>
    </FormDefine>
    

     接下来直接上Java代码

    public void makePdf(String xmlPath, String pdfPath, String resultPath, HashMap<String, String> map)
                throws DocumentException, IOException, Exception {
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            FileOutputStream fileOutputStream = null;
            SAXReader saxReader = new SAXReader();
            if (!this.makedir(resultPath)) {
                System.out.println("创建目录失败");
            } else {
                File xmlfile = new File(xmlPath);
                // dom4j读取xml文件得到根元素
                Element rootElement = saxReader.read(xmlfile).getRootElement();
                // 以文件流形式输入PDF文件
                FileInputStream in = new FileInputStream(pdfPath);
                fileOutputStream = new FileOutputStream(resultPath);
                
                pdfReader = new PdfReader(in);
                pdfStamper = new PdfStamper(pdfReader, fileOutputStream);
               // "Config"xml二級標簽,返回一個迭代器
                for ( Iterator it = this.getElementIterator(rootElement, "Config"); it.hasNext();) {
                    Element element = (Element) it.next();
                    Attribute attributeName = element.attribute("name");
                  
                    String name = "";
                    if (attributeName != null) {
                         name = attributeName.getValue();
                    }
                    
                    String value = "";
                    if (map.containsKey(name)) {
                        value = (String) map.get(name);
                    }  else {
                        continue;
                    }
                    // 獲取node節點個數
                    int count = element.nodeCount();
                    System.out.println(count+"=======");
                    int page = 0;
                    float x = 0;
                    float y = 0;
                    String font = "";
                    int size = 0;
                    for (int j = 0; j < count; j++) {
                        Node node = element.node(j);
                        // 對比該節點是不是一個元素
                        if (node instanceof Element) {
                            if (node.getName().equals("Page"))
                                page = Integer.parseInt(node.getText());
                            if (node.getName().equals("X"))
                                x = Float.parseFloat(node.getText());
                            if (node.getName().equals("Y"))
                                y = Float.parseFloat(node.getText());
                            if (node.getName().equals("Font"))
                                font = node.getText();
                            if (node.getName().equals("Size"))
                                size = Integer.parseInt(node.getText());
                        }
                          
                    }
                    PdfContentByte over;
                    over = pdfStamper.getOverContent(page);
                    over.beginText();
                    BaseFont bfChinese=this.getBaseFont(font);
                    over.setFontAndSize(bfChinese, size);
                    over.setColorFill(Color.blue);
                    /**
                     * 參數説明
                     * 左、右、居中(ALIGN_CENTER, ALIGN_RIGHT or ALIGN_LEFT)
                     * 要输出的文本
                     * 文本输入的X坐标
                     * 文本输入的Y坐标
                     * 文本的旋转角度
                     */
                    over.showTextAligned(PdfContentByte.ALIGN_LEFT, value, x, y, 0);
                    over.endText();
                    System.out.println("結束=====");
                }
                if(pdfReader!=null){
                    try{
                        pdfReader.close();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
                if (pdfStamper != null) {
                    try {
                        pdfStamper.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        private BaseFont getBaseFont(String font) throws com.lowagie.text.DocumentException, IOException {
           
            if("楷体gb2312".equalsIgnoreCase(font)){
                BaseFont bfChinese = BaseFont.createFont("C:/Users/qinda/Desktop/Excel/pdf/test/simkaiGBK.ttf",
                        BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                return bfChinese;
            }
            		return null;
        }
    
        public static boolean makedir(String resultPath) {
          
           try {
               File file = new File(resultPath);
               if(!file.exists()) {
                   System.out.println("目录创建成功。。。。。。。。。。");
                   file.createNewFile();
               }else {
                   System.out.println("目录已存在");
               }
            
        } catch (Exception e) {
          return false;
        }
        return true;
        }  
        
        public static Iterator<Element> getElementIterator(Element rootElement,String elementName){
           Iterator<Element> iterator = null;
           for(Iterator<Element> it = rootElement.elementIterator();it.hasNext();) {
               Element element = it.next();
               if(element.getName().equals(elementName)) {
                   iterator = element.elementIterator();
               }
           }
           return  iterator;
        }
    }
    

      测试代码

      public static void main(String[] args) throws DocumentException, IOException, Exception {
            String resultPath ="C:/Users/qinda/Desktop/Excel/pdf/test/結果.pdf";
            String pdfPath = "C:\Users\qinda\Desktop\pdf\模板.pdf";
            String xmlPath = "C:\Users\qinda\Desktop\pdf\aa.xml";
            HashMap<String,String> map = new HashMap<>();
            map.put("Name", "12345667");
            map.put("CityName", "北京");
            map.put("Bank", "12345667");
            MakePdf makePdf = new MakePdf();
            // map是要插入的數據
            makePdf.makePdf(xmlPath, pdfPath, resultPath,map);
            
        }  

     说明下:需要填充的数据用xml中的<X> <Y>的标签来调整位置。end。。。。。。。。。。。。。。。。

  • 相关阅读:
    一些关于"虚拟交易"的有趣文章
    Windows中的消息队列:Message Queuing (MSMQ)
    ATLStyle模板 不用虚函数实现多态
    AIX 下获取系统CPU及内存的使用情况方法
    关于HPUNIX C 兼容性
    Android进阶Acticivity的启动模式
    ViewState & UpdatePanle & ReadOnly属性
    由网站构架演变说起
    '操作必须使用一个可更新的查询'解决方法
    ScriptManager & ClientScriptManager
  • 原文地址:https://www.cnblogs.com/qinda/p/11042156.html
Copyright © 2011-2022 走看看