PageOffice 开发者中心 PageOffice 开发者中心
首页
文档
  • 后端Java手册 (opens new window)
  • 后端.netcore手册 (opens new window)
  • 前端JavaScript手册 (opens new window)
下载
购买 (opens new window)
首页
文档
  • 后端Java手册 (opens new window)
  • 后端.netcore手册 (opens new window)
  • 前端JavaScript手册 (opens new window)
下载
购买 (opens new window)
  • 开始

  • 通用控制

  • Word

  • Excel

  • PDF

  • FileMaker

    • 后台生成单个Word文档
    • 后台批量生成Word文档
    • 后台生成单个PDF文档
    • 后台批量生成PDF文档
    • 批量转PDF文件
      • 批量生成并打印文件
      • 不打开文件的情况下修改文档指定区域内容
    • PPT

    • 更多

    目录

    批量转PDF文件

    # 批量转PDF文件

    • 查看本示例演示效果

    注意

    本文中展示的代码均为关键代码,复制粘贴到您的项目中,按照实际的情况,例如文档路径,用户名等做适当修改即可使用。

    在实际项目开发中如果遇到批量动态生成PDF文档的需求,只需参考后台批量生成PDF文档,目前网上也有一些针对此需求的方案,如果您想要了解这些方案的对比,请查看后台生成单个Word文档中的“方案对比”。

    如果只是需要批量转PDF文件,那么也可以使用PageOffice提供的FileMaker组件来实现,与“后台批量生成PDF文档”不同的地方仅是:批量转PDF文件不需要WordDocumentWriter对象动态填充数据的代码。所以批量转PDF文件也只需两步即可实现:

    1. 调用FileMakerCtrl对象的fillDocumentAsPDF方法实现Word转PDF功能,比如Convert.jsp中调用了此代码;
    fmCtrl.fillDocumentAsPDF("doc01.doc", DocumentOpenType.Word, "doc01.pdf");
    
    1. 调用PageOffice提供的jsCallFileMaker函数,递归执行Convert.jsp实现批量转PDF文件功能,比如执行下面的ConvertFiles(),递归调用ConvertFile函数,把ids数组中包含的所有Word文件转为pdf。
    var ids = [1, 2, 3, 5]; //比如这是Word文件在数据库中的id
    
    function ConvertFiles() {
    	ConvertFile(ids, 0); 
    }
    
    function ConvertFile(idArr, index) {
    	filemakerctrl.SaveFilePage = "/FileMakerConvertPDFs/SaveFile.jsp?id=" + idArr[index];
    	filemakerctrl.CallFileMaker({
    		url: "/FileMakerConvertPDFs/Convert.jsp?id="+idArr[index], //把指定id的word文件转pdf
    		success: function (customSaveResult) {
    			console.log("completed successfully.");
    			index++;
    			
    			if(index < idArr.length){
    				ConvertFile(idArr, index);
    			} 
    		},
    		progress: function (pos) {
    			console.log("running "+pos+"%");
    		},
    		error: function (msg) {
    			console.log("error occurred: "+msg);
    		}
    	});
    }
    

    FileMakerCtrl 和 PageOfficeCtrl 的区别

    FileMakerCtrl 本质上就是一个没有界面的 PageOfficeCtrl,也是调用客户端 Office 程序处理文件的,都可以实现对文档进行动态填充、动态转 PDF 等功能,唯一的区别就是 FileMakerCtrl 在线打开填充和转换文档的时候,客户端页面不打开显示文档内容,而 PageOfficeCtrl 会打开显示文档内容。

    # 后端代码

    1. 调用FileMakerCtrl对象实现Word转pdf,比如后端/convert方法的代码如下:
      String id = request.getParameter("id").trim();
      String docName = "doc0" + id + ".doc";
      String pdfName = "doc0" + id + ".pdf";
      
      FileMakerCtrl fmCtrl = new FileMakerCtrl(request);
      fmCtrl.fillDocumentAsPDF("doc/" + docName, DocumentOpenType.Word, pdfName);
      out.print(fmCtrl.getHtml());
      
      String id = Request.Query["id"];
      String docName = "doc0" + id + ".doc";
      String pdfName = "doc0" + id + ".pdf";
      
      PageOfficeNetCore.FileMakerCtrl fileMakerCtrl = new PageOfficeNetCore.FileMakerCtrl(Request);
      fileMakerCtrl.FillDocumentAsPDF("doc/" + docName, PageOfficeNetCore.DocumentOpenType.Word, pdfName); 
      ViewBag.FMCtrl = fileMakerCtrl.getHtml();
      
      // Make sure to add code blocks to your code group
      1. Word转pdf后,在SaveFilePage属性指向的地址接口中处理文件保存的后台代码如下:
        FileSaver fs = new FileSaver(request, response);
        fs.saveToFile(request.getSession().getServletContext().getRealPath("FileMakerConvertPDFs/doc/"+ fs.getFileName()));
        fs.setCustomSaveResult("{\"msg\":\"ok\"}");//用于给前端页面返回数据
        fs.close();       
        
        PageOfficeNetCore.FileSaver fs = new PageOfficeNetCore.FileSaver(Request, Response);
        await fs.LoadAsync();
        string webRootPath = _webHostEnvironment.WebRootPath;
        fs.SaveToFile(webRootPath + "/FileMakerConvertPDFs/doc/" + fs.FileName);
        fs.CustomSaveResult = "{\"msg\":\"ok\"}";//用于给前端页面返回数据
        fs.Close();
        
        // Make sure to add code blocks to your code group

        # 前端代码

        调用PageOffice提供的jsCallFileMaker函数,递归执行/convert实现批量转PDF文件功能的前端页面代码,如下:

        <script setup>
        import request from '@/utils/request';
        import { ref, onMounted } from 'vue'
        import { filemakerctrl, POBrowser } from 'js-pageoffice'
        
        const titleText = ref('');
        const checked = ref(true);
        const buttonDisabled = ref(false);
        const progressBar1 = ref(null);
        const progressBar2 = ref(null);
        
        onMounted(async () => {
          try {
            const response = await request({
              url: '/index',
              method: 'get',
            });
            titleText.value = response;
          } catch (error) {
            console.error('Failed to fetch title:', error);
          }
        })
        
        function selectall() {
          if (checked.value) {
            let obj = document.all.check;
            for (let i = 0; i < obj.length; i++) {
              obj[i].checked = true;
              checked.value = false;
            }
          } else {
            let obj = document.all.check;
            for (let i = 0; i < obj.length; i++) {
              obj[i].checked = false;
              checked.value = true;
            }
          }
        }
        
        function ConvertFiles() {
          let ids = [];
          let checkboxes = document.getElementsByName("check");
        
          for (let i = 0; i < checkboxes.length; i++) {
            if (checkboxes[i].checked) {
              ids.push(checkboxes[i].value);
            }
          }
        
          if (0 == ids.length) {
            alert("请至少选择一个文档");
            return;
          }
        
          buttonDisabled.value = true;
          ConvertFile(ids, 0);
        }
        
        function ConvertFile(idArr, index) {
          // 设置用于保存文件的服务器端controller地址,该地址需从"/"开始,指向服务器端根目录  
          /** 如果想要给SaveFilePage传递多个参数,建议使用new URLSearchParams方式,例如:
        * let saveFileUrl = "/FileMakerConvertPDFs/save";
        * let paramValue = new URLSearchParams({id:1,name:"张三"});
        * filemakerctrl.SaveFilePage = `${saveFileUrl}?${paramValue.toString()}`;
        */
          filemakerctrl.SaveFilePage = "/FileMakerConvertPDFs/save?id=" + idArr[index];
          filemakerctrl.CallFileMaker({
            // url:指向服务器端FileMakerCtrl打开文件的controller地址,该地址需从"/"开始,指向服务器端根目录  
            url: "/FileMakerConvertPDFs/convert?id=" + idArr[index],
            success: (res) => {//res:获取服务器端fs.setCustomSaveResult设置的保存结果
              console.log(res);
              console.log("completed successfully.");
              setProgress1(100);
              index++;
              setProgress2(index, idArr.length);
              if (index < idArr.length) {
                ConvertFile(idArr, index);
              }
            },
            progress: (pos) => {
              console.log("running " + pos + "%");
              setProgress1(pos);
            },
            error: (msg) => {
              console.log("error occurred: " + msg);
            },
          });
        }
        
        function setProgress1(percent) {
          progressBar1.value.style.width = percent + "%";
          progressBar1.value.innerText = percent + "%";
        }
        
        function setProgress2(index, count) {
          progressBar2.value.style.width = Math.round((index / count) * 100) + "%";
          progressBar2.value.innerText = index + "/" + count;
        }
        
        </script>
        
        <template>
          <div class="Word">
            <div style="margin: 100px" align="center">
              <h2>演示:批量转PDF</h2>
              <div style="width: 600px; margin: 0 auto; font-size: 14px">
                <p style="text-align: left">
                  操作说明:<br />
                  1. 勾选下面的文件;<br />
                  2. 点击“批量转换PDF文档”按钮;<br />
                  3.生成完毕后,即可在“FileMakerConvertPDFs/doc”目录下看到批量生成的PDF文件。<br />
                </p>
              </div>
              <h3>文件列表</h3>
              <table id="table1">
                <tr>
                  <th>
                    <input name="checkAll" type="checkbox" @click="selectall()" />
                  </th>
                  <th>序号</th>
                  <th>文件名</th>
                </tr>
                <tr>
                  <td><input name="check" type="checkbox" value="1" /></td>
                  <td>01</td>
                  <td>PageOffice产品简介</td>
                </tr>
                <tr>
                  <td><input name="check" type="checkbox" value="2" /></td>
                  <td>02</td>
                  <td>PageOffice产品安装步骤</td>
                </tr>
                <tr>
                  <td><input name="check" type="checkbox" value="3" /></td>
                  <td>03</td>
                  <td>PageOffice产品应用领域</td>
                </tr>
                <tr>
                  <td><input name="check" type="checkbox" value="4" /></td>
                  <td>04</td>
                  <td>PageOffice产品对环境的要求</td>
                </tr>
              </table>
        
              <input type="button" id="Button1" :disabled="buttonDisabled" value="批量转换PDF文档" @click="ConvertFiles()" />
        
              <div id="progressDiv">
                单文件进度:
                <div class="progressBarContainer">
                  <div id="progressBar1" ref="progressBar1" class="progressBar"></div>
                </div>
                整体进度:
                <div class="progressBarContainer">
                  <div id="progressBar2" ref="progressBar2" class="progressBar"></div>
                </div>
              </div>
            </div>
          </div>
        </template>
        
        <style scoped>
        h3 {
          display: block;
          font-size: 1.17em;
          margin-block-start: 1em;
          margin-block-end: 1em;
          margin-inline-start: 0px;
          margin-inline-end: 0px;
          font-weight: bold;
        }
        h2 {
          display: block;
          font-size: 1.5em;
          margin-block-start: 0.83em;
          margin-block-end: 0.83em;
          margin-inline-start: 0px;
          margin-inline-end: 0px;
          font-weight: bold;
        }
        table {
          border: solid 1px #ccc;
          width: 600px;
          margin: 20px;
        }
        th {
          border-bottom: solid 1px #ccc;
          text-align: left;
          padding: 5px;
        }
        td {
          padding: 5px;
        }
        .progressBarContainer {
          width: 100%;
          background-color: #eee;
          border-radius: 5px;
          padding: 3px;
          box-shadow: 2px 2px 3px 3px #ccc inset;
        }
        .progressBar {
          height: 20px;
          width: 0%;
          background-color: #1a73e8;
          border-radius: 5px;
          text-align: center;
          line-height: 20px;
          color: white;
        }
        #progressDiv {
          width: 400px;
          margin: 10px auto;
          text-align: left;
          font-size: 14px;
          border: solid 1px #1a73e8;
          padding: 10px 20px;
          color: #1a73e8;
        }
        </style>
        
        上次更新: 2024/12/05, 13:01:18
        PageOffice | Copyright © 2013-2025 卓正软件 京ICP备12010902号-2 京公网安备 11010502019270号
        • 跟随系统
        • 浅色模式
        • 深色模式
        • 阅读模式