Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 832|回复: 0

[默认分类] java转pdf(html转为pdf),解决中文乱码,标签不规范等问题

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2020-8-2 16:33:30 | 显示全部楼层 |阅读模式
    第一步,下载jar包以及建对应的文件夹。注意pd4ml的jar要选择pro版本。然后建一个pd4fonts.properties
    里面对应的字体。
    1. SimSun = simsun.ttf
    2. 前面为变量名,后面要对应你下载好的字体。网上都有各种字体下载。相应步骤做完了,做完后的文件夹如图格式都有了!
    3. 注意要引入图片中对应的jar下面的三个jar包到项目中去。
    复制代码


      
    以下为从文件读取到数据再作导出功能。

    1. import java.awt.Insets;
    2. import java.io.BufferedInputStream;
    3. import java.io.ByteArrayOutputStream;
    4. import java.io.File;
    5. import java.io.FileInputStream;
    6. import java.io.IOException;
    7. import java.io.StringReader;
    8. import java.net.MalformedURLException;
    9. import java.security.InvalidParameterException;
    10. import org.zefer.pd4ml.PD4Constants;
    11. import org.zefer.pd4ml.PD4ML;
    12. public class Test {
    13.     protected int topValue = 10;
    14.     protected int leftValue = 20;
    15.     protected int rightValue = 10;
    16.     protected int bottomValue = 10;
    17.     protected int userSpaceWidth = 1300;
    18.     /**
    19.      * @param args
    20.      */
    21.     public static void main(String[] args) {
    22.         try {
    23.             Test jt = new Test();
    24.             //此处填写你的html文件
    25.             String html = readFile("/Users/wangchen/Desktop/370fx2.html", "UTF-8");
    26.             //此处填写你下载的地方
    27.             jt.doConversion2(html, "/Users/wangchen/Desktop/370fx2.pdf");
    28.         } catch (Exception e) {
    29.             e.printStackTrace();
    30.         }
    31.     }
    32.     public void doConversion2(String htmlDocument, String outputPath)
    33.             throws InvalidParameterException, MalformedURLException,
    34.             IOException {
    35.         PD4ML pd4ml = new PD4ML();
    36.         pd4ml.enableDebugInfo();
    37.         pd4ml.setHtmlWidth(userSpaceWidth);
    38.         pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));
    39.         pd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue,
    40.                 rightValue));
    41. //此处的classPath注意一定要获取到你放fonts的文件夹。他需要获取到你下载的字体
    42.         String classPath = Test.class.getResource("/")+"fonts";
    43.         pd4ml.useTTF(classPath, true);
    44.         pd4ml.setDefaultTTFs("SimSun", "SimSun", "SimSun");
    45.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
    46.         pd4ml.render(new StringReader(htmlDocument), baos);
    47.         baos.close();
    48.         File output = new File(outputPath);
    49.         java.io.FileOutputStream fos = new java.io.FileOutputStream(output);
    50.         fos.write(baos.toByteArray());
    51.         fos.close();
    52.     }
    53.     private final static String readFile(String path, String encoding)
    54.             throws IOException {
    55.         File f = new File(path);
    56.         FileInputStream is = new FileInputStream(f);
    57.         BufferedInputStream bis = new BufferedInputStream(is);
    58.         ByteArrayOutputStream fos = new ByteArrayOutputStream();
    59.         byte buffer[] = new byte[2048];
    60.         int read;
    61.         do {
    62.             read = is.read(buffer, 0, buffer.length);
    63.             if (read > 0) {
    64.                 fos.write(buffer, 0, read);
    65.             }
    66.         } while (read > -1);
    67.         fos.close();
    68.         bis.close();
    69.         is.close();
    70.         return fos.toString(encoding);
    71.     }
    72. }
    复制代码


      
      
    如上你就可以下载将HTML转为pdf了。任意文本也可以转为pdf,经测试,可用
      
    附件如下:https://pan.baidu.com/s/1wSvBM6Kti4IpI9IlDaycew
      
      
    以下为浏览器下载pdf的工具类。直接调用红色的方法即可。htmlDocument 为你要导出的数据,response为该次请求的响应体,fileName为下载的名字

    1. package com.ccb.common.utils;
    2. import org.apache.commons.io.output.ByteArrayOutputStream;
    3. import org.apache.commons.lang3.StringUtils;
    4. import javax.servlet.http.HttpServletResponse;
    5. import java.awt.*;
    6. import java.io.*;
    7. import java.security.InvalidParameterException;
    8. import org.zefer.pd4ml.PD4Constants;
    9. import org.zefer.pd4ml.PD4ML;
    10. /**
    11. * @author caihong
    12. * @time 2019/1/28
    13. */
    14. public class PDFUtil {
    15.     private static String PDF_TYPE="application/pdf";
    16.     private static String classpath=PDFUtil.class.getResource("/").getPath();
    17.     protected static int topValue = 10;
    18.     protected static int leftValue = 20;
    19.     protected static int rightValue = 10;
    20.     protected static int bottomValue = 10;
    21.     protected static int userSpaceWidth = 1300;
    22.     public static void pdf4htmlToPdf(String htmlDocument,HttpServletResponse response, String filename)throws InvalidParameterException,
    23.             IOException {
    24.         PD4ML pd4ml = new PD4ML();
    25.         pd4ml.enableDebugInfo();
    26.         pd4ml.setHtmlWidth(userSpaceWidth);
    27.         pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));
    28.         pd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue,rightValue));
    29.         pd4ml.useTTF(classpath+"fonts", true);
    30.         pd4ml.setDefaultTTFs("SimSun", "SimSun", "SimSun");
    31.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
    32.         pd4ml.render(new StringReader(htmlDocument), baos);
    33.         baos.close();
    34.         renderPdf(response,baos.toByteArray(),filename);
    35.     }
    36.     public static void renderPdf(HttpServletResponse response, final byte[] bytes, final String filename) {
    37.         initResponseHeader(response, PDF_TYPE);
    38.         setFileDownloadHeader(response, filename, ".pdf");
    39.         if (null != bytes) {
    40.             try {
    41.                 response.getOutputStream().write(bytes);
    42.                 response.getOutputStream().flush();
    43.             } catch (IOException e) {
    44.                 throw new IllegalArgumentException(e);
    45.             }
    46.         }
    47.     }
    48.     /**
    49.      * 分析并设置contentType与headers.
    50.      */
    51.     private static HttpServletResponse initResponseHeader(HttpServletResponse response, final String contentType, final String... headers) {
    52.         // 分析headers参数
    53.         String encoding = "utf-8";
    54.         boolean noCache = true;
    55.         for (String header : headers) {
    56.             String headerName = StringUtils.substringBefore(header, ":");
    57.             String headerValue = StringUtils.substringAfter(header, ":");
    58.             if (StringUtils.equalsIgnoreCase(headerName, "utf-8")) {
    59.                 encoding = headerValue;
    60.             } else if (StringUtils.equalsIgnoreCase(headerName, "no-cache")) {
    61.                 noCache = Boolean.parseBoolean(headerValue);
    62.             } else {
    63.                 throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
    64.             }
    65.         }
    66.         // 设置headers参数
    67.         String fullContentType = contentType + ";charset=" + encoding;
    68.         response.setContentType(fullContentType);
    69.         if (noCache) {
    70.             // Http 1.0 header
    71.             response.setDateHeader("Expires", 0);
    72.             response.addHeader("Pragma", "no-cache");
    73.             // Http 1.1 header
    74.             response.setHeader("Cache-Control", "no-cache");
    75.         }
    76.         return response;
    77.     }
    78.     /**
    79.      * 设置让浏览器弹出下载对话框的Header.
    80.      * @param
    81.      */
    82.     public static void setFileDownloadHeader(HttpServletResponse response, String fileName, String fileType) {
    83.         try {
    84.             // 中文文件名支持
    85.             String encodedfileName = new String(fileName.getBytes("GBK"), "ISO8859-1");
    86.             response.setHeader("Content-Disposition", "attachment; filename="" + encodedfileName + fileType + """);
    87.         } catch (UnsupportedEncodingException e) {
    88.         }
    89.     }
    90.     private final static String readFile(String path, String encoding)
    91.             throws IOException {
    92.         File f = new File(path);
    93.         FileInputStream is = new FileInputStream(f);
    94.         BufferedInputStream bis = new BufferedInputStream(is);
    95.         java.io.ByteArrayOutputStream fos = new java.io.ByteArrayOutputStream();
    96.         byte buffer[] = new byte[2048];
    97.         int read;
    98.         do {
    99.             read = is.read(buffer, 0, buffer.length);
    100.             if (read > 0) {
    101.                 fos.write(buffer, 0, read);
    102.             }
    103.         } while (read > -1);
    104.         fos.close();
    105.         bis.close();
    106.         is.close();
    107.         return fos.toString(encoding);
    108.     }
    109. }
    复制代码


      
    自己完成controller,以及mapping映射后,注意要用get请求
    http://localhost:8080/api/img/exportPdf?htmlDocument=12%E7%9A%84%E5%8F%91%E9%A1%BA%E4%B8%B0%E9%98%BF%E6%96%AF%E9%A1%BF%E5%8F%91%E9%80%81%E5%88%B0%E5%8F%91%E9%80%81%E5%A4%A7&fileName=123
    便可以下载pdf了
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-4-25 09:03 , Processed in 0.327888 second(s), 37 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表