itext怎么将js导出pdf

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了itext怎么将js导出pdf相关的知识,希望对你有一定的参考价值。

参考技术A

html转成PDF:
1.下载HTML2FPDF开源软件,将其放在你的网站根目录文件夹下,比如 /srv/httpd/htdocs/test/;

  2.新建1.php文件,1.php中的代码如下:
  <?php
  require('html2fpdf.php');
  $pdf=new HTML2FPDF();
  $pdf->AddPage();
  // yourfile.html 你要转化的HTML文件
  $yourfile_html = "yourfile.html"
  // yourfile.pdf 转化成功后的pdf文件名
  $yourfile_pdf = "yourfile.pdf"
  $fp = fopen($yourfile_html,"r");
  $strContent = fread($fp, filesize($yourfile_html));
  fclose($fp);
  $pdf->WriteHTML($strContent);
  $pdf->Output($yourfile_pdf );
  echo "PDF 文件成功生成!";
  3.将你要转化的yourfile.html文件也放在test目录下,随后在浏览器中访问1.php文件就可以把html文件转化成PDF文件了,
  注意事项:1.php,yourfile.html和html2fpdf.php都要在同一目录下

参考技术B 1 <div id="divPDF">
2 需要截图的区域
3 </div>
JS
1 <script src="../Js/html2canvas.js"></script>
2 <script type="text/javascript">
3
4 function getPDF()
5 html2canvas($('#divPDF'),
6
7 onrendered: function (canvas)
8 var imgUrl = canvas.toDataURL();//获取截图的Base64编码
9
10 );
11
12
13 </script>
后台使用图片 Base64编码转换为图像
1 // <summary>
2 /// Base64编码转换为图像
3 /// </summary>
4 /// <param name="base64String">Base64字符串</param>
5 /// <returns>转换成功返回图像;失败返回null</returns>
6 public string Base64ToImage(string imgName, string base64String, string path)
7
8 base64String = base64String.Replace("data:image/png;base64,", "");
9 MemoryStream ms = null;
10 System.Drawing.Image image = null;
11 string imgUrl = path + "\\" + imgName + ".png";
12 byte[] imageBytes = Convert.FromBase64String(base64String);
13 ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
14 ms.Write(imageBytes, 0, imageBytes.Length);
15 image = System.Drawing.Image.FromStream(ms, true);
16 image.Save(imgUrl);
17 return imgUrl;
18
给PDF文件添加水印ITextWaterMark
1 public void AddWaterMark(string fileLocation, string path, int x, int y)
2
3 string WatermarkLocation = path + "\\watermark.png";
4 Document document = new Document();
5 PdfReader pdfReader = new PdfReader(fileLocation);
6 PdfStamper stamp = new PdfStamper(pdfReader, new FileStream(fileLocation.Replace(".pdf", "[temp][file].pdf"), FileMode.Create));
7
8 iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(WatermarkLocation);
9 img.SetAbsolutePosition(x, y); // set the position in the document where you want the watermark to appear (0,0 = bottom left corner of the page)
10 PdfContentByte waterMark;
11 for (int page = 1; page <= pdfReader.NumberOfPages; page++)
12
13 waterMark = stamp.GetOverContent(page);
14 waterMark.AddImage(img);
15
16 stamp.FormFlattening = true;
17 stamp.Close();
18 pdfReader.Close();
19 // now delete the original file and rename the temp file to the original file
20 File.Delete(fileLocation);
21 File.Move(fileLocation.Replace(".pdf", "[temp][file].pdf"), fileLocation);
22
23

IText_根据模板导出PDF(文字表格图片)

1、引入jar包

		<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.4.3</version>
        </dependency>

2、新建word文档,创建模板,将文件另存为pdf,并用Adobe Acrobat DC打开

3、在需要插入数据的空白处,右击,点击【文本域】,将文本域拖放到你想要的位置,更改域名称为你传入的变量名。

4、模板(编辑好后的模板)

5、保存模板,将模板放到项目中

pdf生成,代码如下

public static void creatPdf(Map<String, Object> map, String filePath) 
        try 
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            FileOutputStream out = new FileOutputStream(filePath);// 输出流
            // 读取pdf模板
//            PdfReader reader = new PdfReader(TemplateToWord.class.getResource("/com/cn/business/templates/report.pdf"));
            PdfReader reader = new PdfReader(String.valueOf(map.get("tempPath")));
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            PdfStamper stamper = new PdfStamper(reader, bos);
            stamper.setFormFlattening(true);
            AcroFields form = stamper.getAcroFields();
            // 文字类的内容处理
            Map<String, String> datemap = (Map<String, String>) map.get("dataMap");
            form.addSubstitutionFont(bf);
            for (String key : datemap.keySet()) 
                String value = datemap.get(key);
                form.setField(key, value);
            
            // 图片类的内容处理
            Map<String, String> imgmap = (Map<String, String>) map.get("imgMap");
            for (String key : imgmap.keySet()) 
                String value = imgmap.get(key);
                String imgpath = value;
                int pageNo = form.getFieldPositions(key).get(0).page;
                Rectangle signRect = form.getFieldPositions(key).get(0).position;
                float x = signRect.getLeft();
                float y = signRect.getBottom();
                // 根据路径读取图片
                Image image = Image.getInstance(imgpath);
                // 获取图片页面
                PdfContentByte under = stamper.getOverContent(pageNo);
                // 图片大小自适应
                image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                // 添加图片
                image.setAbsolutePosition(x, y);
                under.addImage(image);
            
            // 表格类
            Map<String, List<List<String>>> listMap = (Map<String, List<List<String>>>) map.get("tableList");
            for (String key : listMap.keySet()) 
                List<List<String>> lists = listMap.get(key);
                int pageNo = form.getFieldPositions(key).get(0).page;
                PdfContentByte pcb = stamper.getOverContent(pageNo);
                Rectangle signRect = form.getFieldPositions(key).get(0).position;
                //表格位置
                int column = lists.get(0).size();
                int row = lists.size();
                PdfPTable table = new PdfPTable(column);
                float tatalWidth = signRect.getRight() - signRect.getLeft() - 1;
                int size = lists.get(0).size();
                float width[] = new float[size];
                for (int i = 0; i < size; i++) 
                    if (i == 0) 
                        width[i] = 60f;
                     else 
                        width[i] = (tatalWidth - 60) / (size - 1);
                    
                
                table.setTotalWidth(width);
                table.setLockedWidth(true);
                table.setKeepTogether(true);
                table.setSplitLate(false);
                table.setSplitRows(true);
                Font FontProve = new Font(bf, 10, 0);
                //表格数据填写
                for (int i = 0; i < row; i++) 
                    List<String> list = lists.get(i);
                    for (int j = 0; j < column; j++) 
                        Paragraph paragraph = new Paragraph(String.valueOf(list.get(j)), FontProve);
                        PdfPCell cell = new PdfPCell(paragraph);
                        cell.setBorderWidth(1);
                        cell.setVerticalAlignment(Element.ALIGN_CENTER);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        cell.setLeading(0, (float) 1.4);
                        table.addCell(cell);
                    
                
                table.writeSelectedRows(0, -1, signRect.getLeft(), signRect.getTop(), pcb);
            
            stamper.setFormFlattening(true);        // 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            int pageNum = reader.getNumberOfPages();
            for (int i = 1; i <= pageNum; i++) 
                PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
                copy.addPage(importPage);
            
            doc.close();
         catch (IOException e) 
            System.out.println(e);
         catch (DocumentException e) 
            System.out.println(e);
        

    

6、测试方法

public static void main(String[] args) 
        // 模板路径
        String tempPath = "D:\\\\admin\\\\test.pdf";

        //文字类
        Map<String, String> dataMap = new HashMap<String, String>();
        DateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String title = "测试文字内容" + "(" + format.format(new Date()) + ")";
        dataMap.put("title", title);		// dataMap中的key要和模板中的域名对应

        //图片
        String imgPath = "C:\\\\Users\\\\Admin\\\\Pictures\\\\豚鼠图片.jpg";
        Map<String, String> imgMap = new HashMap<String, String>();
        imgMap.put("picture", imgPath);		// imgMap中的key要和模板中的域名对应

        //表格 一行数据是一个list
        List<String> list = new ArrayList<String>();
        list.add("日期");
        list.add("金额");

        List<String> list2 = new ArrayList<String>();
        list2.add("2021-08-27");
        list2.add("100000");

        List<List<String>> List = new ArrayList<List<String>>();
        List.add(list);
        List.add(list2);

        Map<String, List<List<String>>> listMap = new HashMap<String, List<List<String>>>();
        listMap.put("table", List);		// 这里的listMap中key要和模板中的域名对应

        Map<String, Object> o = new HashMap<String, Object>();
        o.put("tempPath", tempPath);
        o.put("dataMap", dataMap);
        o.put("imgMap", imgMap);
        o.put("tableList", listMap);

        String outPutPath = "D:\\\\admin\\\\test1.pdf";
        creatPdf(o, outPutPath);
    

7、效果图

8、结语

itext的功能不单单只有这些,当然,这些也是比较常用的,另外还有合并PDF文件,以及生成带水印或背景的PDF,如果有需要,我也可以贴出来

原创不易,如果对你有帮助,一键三连吧

以上是关于itext怎么将js导出pdf的主要内容,如果未能解决你的问题,请参考以下文章

java利用itext导出pdf

freemarket+itext+springboot将html静态页面渲染后导出为pdf文件

Java利用itext实现导出PDF文件

Java利用itext实现导出PDF文件

IText_根据模板导出PDF(文字表格图片)

IText_根据模板导出PDF(文字表格图片)