美文网首页
iText通过html生成pdf(包含中文,css)

iText通过html生成pdf(包含中文,css)

作者: 想揉娜娜奇的脸 | 来源:发表于2017-06-05 19:19 被阅读0次
            <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itextpdf</artifactId>
                <version>5.5.11</version>
            </dependency>
            <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itext-asian</artifactId>
                <version>5.2.0</version>
            </dependency>
            <dependency>
                <groupId>com.itextpdf.tool</groupId>
                <artifactId>xmlworker</artifactId>
                <version>5.5.11</version>
            </dependency>
    
      @RequestMapping("pdf")
      public void pdf(HttpServletRequest request, HttpServletResponse response, String html) {
        Document document = new Document(PageSize.LETTER);
        try {
          response.setContentType("application/pdf");
          PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
          document.open();
          InputStream htmlStream = new ByteArrayInputStream(html.getBytes());
          InputStream cssStream = request.getServletContext().getResourceAsStream("/resources/css/pdf.css");
          XMLWorkerHelper.getInstance().parseXHtml(writer, document, htmlStream , cssStream , new XMLWorkerFontProvider() {
            @Override
            public Font getFont(final String fontname, final String encoding, final boolean embedded, final float size, final int style, final BaseColor color) {
              BaseFont bf = null;
              try {
                bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
              } catch (Exception e) {
                e.printStackTrace();
              }
              Font font = new Font(bf, size, style, color);
              font.setColor(color);
              return font;
            }
          });
        } catch (DocumentException | IOException e) {
          e.printStackTrace();
        }
        document.close();
      }
    

    相关文章

      网友评论

          本文标题:iText通过html生成pdf(包含中文,css)

          本文链接:https://www.haomeiwen.com/subject/jikwfxtx.html