日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java 模板生成pdf文件

發布時間:2023/12/10 编程问答 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java 模板生成pdf文件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

java 模板生成pdf文件

  • 1.準備工作
    • 1.1 安裝Adobe Acrobat pro軟件:用來制作導出模板
    • 1.2 用word 制作自己需要的模板,轉成pdf格式
    • 1.3 使用Adobe Acrobat pro打開PDF
    • 1.4 復選框勾選
  • 2.java代碼
    • 2.1 pom文件
    • 2.2生成代碼
    • 2.3 輸出到本地
    • 2.4 瀏覽器下載 (ajax請求無法下載)

1.準備工作

1.1 安裝Adobe Acrobat pro軟件:用來制作導出模板

1.2 用word 制作自己需要的模板,轉成pdf格式



1.3 使用Adobe Acrobat pro打開PDF


1.4 復選框勾選

鏈接: 復選框勾選.

2.java代碼

2.1 pom文件

<!-- pdf樣式 --><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency><!--pdf相關操作--><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.10</version></dependency>

2.2生成代碼

/*** 生成pdf文件** @param map 模板中數據的鍵值對 map 中存入兩個鍵值對 文字填充("data",Map)圖片填充("image",Map)* @param templatePath 模板路徑* @return*/public static ByteArrayOutputStream generatePdf(Map<String, Map> map, String templatePath) {//生產pdfreaderPdfReader reader = null;try {reader = new PdfReader(templatePath);ByteArrayOutputStream bos = new ByteArrayOutputStream();/* 讀取*/PdfStamper pdfStamper = new PdfStamper(reader, bos);/*設置字體格式*/BaseFont baseFont = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);ArrayList<BaseFont> fontList = new ArrayList<>();fontList.add(baseFont);AcroFields s = pdfStamper.getAcroFields();s.setSubstitutionFonts(fontList);/*Field , 這個是自己在pdf上定義的變量名稱*/// 處理數據Map data = map.get("data");for (Map.Entry<String, AcroFields.Item> entry : s.getFields().entrySet()) {if (!CollectionUtils.isEmpty(data) && data.get(entry.getKey()) != null) {s.setField(entry.getKey(), data.get(entry.getKey()).toString(), true);}}// 處理圖片Map imageMap = map.get("image");for (Map.Entry<String, AcroFields.Item> entry : s.getFields().entrySet()) {if (!CollectionUtils.isEmpty(imageMap) && imageMap.get(entry.getKey()) != null) {String key = entry.getKey();String value = imageMap.get(entry.getKey()).toString();int pageNo = s.getFieldPositions(key).get(0).page;Rectangle signRect = s.getFieldPositions(key).get(0).position;float x = signRect.getLeft();float y = signRect.getBottom();//根據路徑讀取圖片Image image = Image.getInstance(value);//獲取圖片頁面PdfContentByte under = pdfStamper.getOverContent(pageNo);//圖片大小自適應image.scaleToFit(signRect.getWidth(), signRect.getHeight());//添加圖片image.setAbsolutePosition(x, y);under.addImage(image);}}pdfStamper.setFormFlattening(true);pdfStamper.close();return bos;} catch (Exception e) {log.info("pdf文件生成失敗");e.printStackTrace();}return null;}

2.3 輸出到本地

/*** 輸出本地** @param bos pdf字節流* @throws DocumentException* @throws IOException*/private void extracted(ByteArrayOutputStream bos) {Document doc = new Document();// 輸出流FileOutputStream out = null;try {// 本地輸出路徑(可根據自己需要自定義)out = new FileOutputStream("F:\\" + System.currentTimeMillis() + ".pdf");PdfCopy copy = new PdfCopy(doc, out);doc.open();PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);copy.addPage(importPage);doc.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (DocumentException e) {e.printStackTrace();}catch (IOException e){e.printStackTrace();}}

2.4 瀏覽器下載 (ajax請求無法下載)

/*** 瀏覽器下載** @param response* @param request* @param fileName 下載的文件名* @param bos paf字節流* @return*/public static void getResponse(HttpServletResponse response, HttpServletRequest request, String fileName, ByteArrayOutputStream bos) {try {//將文件讀入文件流InputStream inStream = new ByteArrayInputStream(bos.toByteArray());//獲得瀏覽器代理信息final String userAgent = request.getHeader("USER-AGENT");//判斷瀏覽器代理并分別設置響應給瀏覽器的編碼格式String finalFileName = null;if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Trident")) {//IE瀏覽器finalFileName = URLEncoder.encode(fileName, "UTF8");} else if (StringUtils.contains(userAgent, "Mozilla")) {//google,火狐瀏覽器finalFileName = new String(fileName.getBytes(), "ISO8859-1");} else {//其他瀏覽器finalFileName = URLEncoder.encode(fileName, "UTF8");}//設置HTTP響應頭//告知瀏覽器下載文件,而不是直接打開,瀏覽器默認為打開response.setContentType("application/x-download");//下載文件的名稱response.addHeader("Content-Disposition", "attachment;filename=\"" + finalFileName + "\"");// 循環取出流中的數據byte[] b = new byte[1024];int len;while ((len = inStream.read(b)) > 0) {ServletOutputStream outputStream = response.getOutputStream();outputStream.write(b, 0, len);outputStream.flush();}inStream.close();response.getOutputStream().close();} catch (Exception e) {throw new CustomException("瀏覽器下載失敗");}}

總結

以上是生活随笔為你收集整理的java 模板生成pdf文件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。