java程序通過 pdf模板 添加pdf表單數據並打印

1:用adobe acrobat設置pdf的表單屬性


第二步:寫java程序


package document.pdf;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

public class OperatePdf {
    public static void main(String[] args) {
        fromPDFTempletToPdfWithValue();
    }
    
    
    public static void fromPDFTempletToPdfWithValue(){
        String fileName = "f:/test.pdf";
        
        try {
            //獲得pdf閱讀器
            PdfReader reader = new PdfReader(fileName);
            //字節數組輸出流
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            
            PdfStamper ps = new PdfStamper(reader,bos);
            
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            //設置中文12號字體
            Font fontChinese = new Font(bf,12,Font.NORMAL);
            //自定義表單
            AcroFields form = ps.getAcroFields();
            
            String str = "黑龍江沙河科技";
            if(str.length()>6)
                str = str.substring(0,6);
            form.setField("company", str);
            
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = format.format(date);
            form.setField("date", dateStr);
            
            List<List<String>> lists = new ArrayList<List<String>>();
            List<String> list = new ArrayList<String>();
            for (int j = 0; j <5; j++) {
                list.add("張三"+(j+1));
                list.add("經理"+(j+1));
                list.add("身份證");
                list.add("4111111111111");
                lists.add(list);
            }
            for(int i=0;i<lists.size();i++){
                List<String> list2 = lists.get(i);
                form.setField("seq"+(i+1),String.valueOf(i+1));
                form.setField("name"+i,list2.get(0));
                form.setField("position"+i,list2.get(1));
                form.setField("certificate"+i,list2.get(2));
                form.setField("number"+i,list2.get(3));
            }
            // 設置爲true/false在點擊生成的pdf文檔的填充域時有區別,
            ps.setFormFlattening(true);
            ps.close();
            FileOutputStream fos = new FileOutputStream("f:/1.pdf");
            fos.write(bos.toByteArray());
            
        } catch (IOException | DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

}

public static void printFile(String path) throws Exception {
        File file = new File(path);
        File[] fies=file.listFiles();
            for(File f:fies){
            System.out.println("file "+f.getName());
                 String fileExt=f.getName().substring(f.getName().indexOf(".")+1,f.getName().length());
                  if("pdf".equalsIgnoreCase(fileExt)){
                    String filepath=path+File.separator+f.getName();
                    File pdfFile=new File(filepath);
                    //構建打印請求屬性集
                    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
                    //設置打印格式,因爲未確定文件類型,這裏選擇AUTOSENSE
                    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
                    //查找所有的可用打印服務
                    PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
                    //定位默認的打印服務
                    PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
                     //顯示打印對話框  
                    //PrintService service = ServiceUI.printDialog(null, 200, 200, printService,   defaultService, flavor, pras);
                    if(defaultService!=null){
                        DocPrintJob job = defaultService.createPrintJob(); //創建打印作業
                        FileInputStream fis = new FileInputStream(pdfFile); //構造待打印的文件流
                        DocAttributeSet das = new HashDocAttributeSet();
                        Doc doc = new SimpleDoc(fis, flavor, das); //建立打印文件格式
                        job.print(doc, pras); //進行文件的打印
                    }
                    f.delete();
            }
        }
      }

發佈了39 篇原創文章 · 獲贊 8 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章