如何在java中利用富文本生成pdf文件

发布时间:2021-02-18 17:11:14 作者:Leah
来源:亿速云 阅读:1216

如何在java中利用富文本生成pdf文件?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

public class PdfUtil {

  public static Boolean htmlToPdf(GuideBook guideBook, String pdfPath) {
    try {
      // 1.新建document
      Document document = new Document();
      // 2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
      //创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
      // 3.打开文档
      document.open();
      //要解析的html
      //html转换成普通文字,方法如下:
      org.jsoup.nodes.Document contentDoc = Jsoup.parseBodyFragment(getHtml(guideBook.getTitle())+guideBook.getContent());
      org.jsoup.nodes.Document.OutputSettings outputSettings = new org.jsoup.nodes.Document.OutputSettings();
      outputSettings.syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
      contentDoc.outputSettings(outputSettings);
      String parsedHtml = contentDoc.outerHtml();
      //这儿的font-family不支持汉字,{font-family:仿宋} 是不可以的。
      InputStream cssIs = new ByteArrayInputStream("* {font-family: PingFang-SC-Medium.otf;}".getBytes("UTF-8"));
      //第四个参数是html中的css文件的输入流
      //第五个参数是字体提供者,使用系统默认支持的字体时,可以不传。
      XMLWorkerHelper.getInstance().parseXHtml(writer, document, new ByteArrayInputStream(parsedHtml.getBytes()), cssIs);
      // 5.关闭文档
      document.close();
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }

  /*
   * 下载文件
   **/
  public static void download(HttpServletRequest request, HttpServletResponse response, InputStream inputStream, String fileName){
    BufferedOutputStream bos = null;
    try {
      // 定义输出缓冲 10k
      byte[] buffer = new byte[10240];
      //文件名称的处理
      // http://127.0.0.1:5002/guide-book/pdf?id=124
      fileName = fileName.replaceAll("[\\pP\\p{Punct}]", "-").replace(" ", "-").replaceAll("[-]+", "-")+".pdf";
      String userAgent = request.getHeader("user-agent").toLowerCase();
      if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
        fileName = URLEncoder.encode(fileName, "UTF-8");
      } else {
        fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
      }
      response.setCharacterEncoding("utf-8");
      response.setContentType("application/msword");
      response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
      bos = new BufferedOutputStream(response.getOutputStream());
      int bytesRead = 0;
      while ((bytesRead = inputStream.read(buffer)) != -1) {
        bos.write(buffer, 0, bytesRead);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (bos != null) {
        try {
          bos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  /*
   * 获取html
   **/
  public static String getHtml(String title){
    return "<h2 align=\"center\">"+title+"</h2>";
  }

}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. 如何在Java中生成Access文件
  2. 如何在Java中利用icepdf将pdf文件按页转换为图片

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:如何在jquery中利用name获取select选中的值

下一篇:使用React怎么根据宽度自适应高度

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》