java中將表單轉換為PDF

來源:互聯網
上載者:User

標籤:for   中文字型   賦值   布局   定位   public   div   pdf   系統   

經過網上搜尋大概有三種方式:PDF模板資料填充,html代碼轉換pdf,借用wkhtmltopdf工具一 .PDF模板資料填充1.建立word,在word中做出和表單一樣的布局的空表單,然後另存新檔pdf;2.用pdf編輯工具,用準備表單這個工具在需要填充動態資料的地方設定文字框或映像框,起好標籤名。3.根據標籤名向pdf中插入資料,並將PDF匯出在指定位置。
            String rootPath="d:/";            String path=rootPath+"dzyjjsdjd.pdf";            System.out.println("電子檔案移交與接收登記單模板位置:"+path);            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//設定日期格式            String newPath=rootPath+df.format(new Date())+"dzyjjsdjd.pdf";            //讀入pdf表單            PdfReader reader = new PdfReader(path);            //根據表單產生一個新的pdf            PdfStamper ps = new PdfStamper(reader,new FileOutputStream(newPath));            //擷取pdf表單            AcroFields s = ps.getAcroFields();            //給表單添加中文字型 這裡採用系統字型。不設定的話,中文可能無法顯示            BaseFont bf = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);            s.addSubstitutionFont(bf);            //遍曆pdf表單表格,同時給表格賦值            Map<String,String> paraMap=getMapData(accept);//自己的資料,按模板中設定的表單標籤封裝進map             for (String key : paraMap.keySet()) {                   if(key.equals("yz1")){//擷取標籤為yz1的pdf標籤,設定其值                     String value = paraMap.get(key);                     tempImgPath1=rootPath+"yz1.png";                     insertImage(ps, tempImgPath1,"yz1",s);                     //圖片插入後需要去除掉設定的這個圖片框,否則會遮當前插入的圖片                     s.removeField("yz1");                 }else{                     String value = paraMap.get(key);                       s.setField(key, value); // 為欄位賦值,注意欄位名稱是區分大小寫                    }                                 }             ps.setFormFlattening(true); // 這句不能少            ps.close();            reader.close();
/**     * 向pdf中插入圖片     * @param ps pdf對象     * @param img 需要插入的圖片路徑     * @param col 需要插入圖片的pdf欄位標籤名     * @param s   pdf欄位     */    public void insertImage(PdfStamper ps, String img,String col,AcroFields s){          try{            List<AcroFields.FieldPosition> list = s.getFieldPositions(col);              Rectangle signRect = list.get(0).position;                                          Image image = Image.getInstance(img);              PdfContentByte under = ps.getOverContent(1); //要插入圖片的頁數,現在只有1頁             float x = signRect.getLeft();              float y = signRect.getBottom();              System.out.println(x);              System.out.println(y);              image.setAbsolutePosition(x, y);              image.scaleToFit(signRect.getWidth(), signRect.getHeight());                            under.addImage(image);         }          catch (Exception e){              // TODO Auto-generated catch block              e.printStackTrace();          }     }  
/** * 插入文本 *  * @return * @author WangMeng * @date 2016年6月16日 */  public static void insertText(PdfStamper ps, AcroFields s)  {  List<AcroFields.FieldPosition> list = s.getFieldPositions("CONNECT_NAME");  Rectangle rect = list.get(0).position;      PdfContentByte cb = ps.getOverContent(1);  PdfPTable table = new PdfPTable(1);  float tatalWidth = rect.getRight() - rect.getLeft() - 1;  table.setTotalWidth(tatalWidth);      PdfPCell cell = new PdfPCell(new Phrase(CreateChunk()));  cell.setFixedHeight(rect.getTop() - rect.getBottom() - 1);  cell.setBorderWidth(0);  cell.setVerticalAlignment(Element.ALIGN_MIDDLE);  cell.setHorizontalAlignment(Element.ALIGN_CENTER);  cell.setLeading(0, (float) 1.1);      table.addCell(cell);  table.writeSelectedRows(0, -1, rect.getLeft(), rect.getTop(), cb);  }  

第二種:將html代碼轉換為pdf

import java.io.ByteArrayInputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import com.itextpdf.text.Document;import com.itextpdf.text.PageSize;import com.itextpdf.text.pdf.PdfWriter;import com.itextpdf.tool.xml.XMLWorkerHelper;public class HtmlToPDF {    public static void main(String[] args) {        try {            Document document = new Document(PageSize.LETTER);            PdfWriter pdfWriter = PdfWriter.getInstance(document,                    new FileOutputStream("c://temp//testpdf.pdf"));            document.open();            document.addAuthor("ysjiang");            document.addCreator("ysjiang");            document.addSubject("test");            document.addCreationDate();            document.addTitle("XHTML to PDF");            XMLWorkerHelper worker = XMLWorkerHelper.getInstance();            String str = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"                    + "<html xmlns=\"http://www.w3.org/1999/xhtml\">"                    + "<head>"                    + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"                    + "<title>HTML 2 PDF</title>"                    + "<style type=\"text/css\">"                    + "<!--"                    + "body {"                    + "    margin: 20px;"                    + "}"                    + "-->"                    + "</style>"                    + "</head>"                    + "<body>"                    + "<div style=\"width:90%; height:160px;\">多情浪漫的人,其實內心的情感是非常脆弱的,感情的末梢,有那麼一點兒敏感,還有那麼一點兒想入非非。所以和浪漫多情的人在一起,言語一定要斯文,說話不能像火炮,態度一定要溫柔、語氣也要婉轉。遇到對方的一個眼神,也許有些人並沒發現什麼端倪,但是放在懂得浪漫的人身上,就會體會出萬種滋味,百般柔情來。"                    + "</div>"                    + "<hr/>"                    + "<table cellspacing=\"0\" cellpadding=\"0\" style=\"width:100%; border:1px;\">"                    + "  <tr>"                    + "  <td style=\"width:30%\">table中的中文顯示及換行"                    + "  </td>"                    + "  <td>多情浪漫的人,其實內心的情感是非常脆弱的,感情的末梢,有那麼一點兒敏感,還有那麼一點兒想入非非。所以和浪漫多情的人在一起,言語一定要斯文,說話不能像火炮,態度一定要溫柔、語氣也要婉轉。遇到對方的一個眼神,也許有些人並沒發現什麼端倪,但是放在懂得浪漫的人身上,就會體會出萬種滋味,百般柔情來。"                    + "  </td>"                    + "  </tr>"                    + "  <tr>"                    + "  <td colspan=\"2\">"                    + "      <img src=\"0.jpg\" />"                    + "  </td>"                    + "  </tr>"                    + "</table>" + "</body>" + "</html>";            // worker.parseXHtml(pdfWriter, document, new FileInputStream("C:\\tmp\\a.htm"), null, new AsianFontProvider());            String url="G:/workProject_ces/zjdzyjjsxt/WebRoot/module/receive/register/input.jsp?pid=4&sign=0&tagg=undo&workitemId=149982394754705&activityName=rk&returnReason=&activityId=receive&time=Mon Jul 17 2017 14:25:49 GMT+0800 (??-???? ???????é?′)";            worker.parseXHtml(pdfWriter, document, new ByteArrayInputStream(str.getBytes()), null, new AsianFontProvider());              XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document,                        new FileInputStream(url));            document.close();            System.out.println("Done.");        } catch (Exception e) {            e.printStackTrace();        }    }}

第三種參照http://blog.csdn.net/zhangkezhi_471885889/article/details/52184700,因為要藉助外部工具,所以部署時候會稍微麻煩點,根據需要選自己的方式

java中將表單轉換為PDF

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.