美文网首页
前端pdf文件预览下载

前端pdf文件预览下载

作者: 林思念 | 来源:发表于2023-12-20 15:08 被阅读0次

常用的前端生成PDF 文件方法

1、方法一

html2canvas + jsPdf的方法将HTML 转换成图片后,在将图转PDF文件

适用场景:适用单页PDF文件,且终端设备一致

示例代码:
HTML:

<html>
  <body>
    <header>This is the header</header>
    <div id="content">
      This is the element you only want to capture
    </div>
    <button id="print">Download Pdf</button>
    <footer>This is the footer</footer>
  </body>
</html>

CSS:

body {
  background: beige;
}
header {
  background: red;
}
footer {
  background: blue;
}
#content {
  background: yellow;
  width: 70%;
  height: 100px;
  margin: 50px auto;
  border: 1px solid orange;
  padding: 20px;
}

JS:

<script src="./jspdf@2.5.1.umd.js"></script>
<script src="./html2canvas@1.4.1.js"></script>
let print = document.getElementById('print')
    print.addEventListener('click', function () {
        let dom = document.getElementById("content")
        var w = dom.offsetWidth;
        var h = dom.offsetHeight;
        console.log(html2canvas, dom)
        html2canvas(dom, {
            dpi: 96, //分辨率
            scale: 2, //设置缩放
            useCORS: true, //允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。,
            //backgroundColor:'#ffffff',这样背景还是黑的
            bgcolor: "#ffffff", //应该这样写
            logging: false, //打印日志用的 可以不加默认为false
        }).then((canvas) => {
            console.log('onrendered', canvas)
            var img = canvas.toDataURL("image/jpeg", 1);
            console.log(img)
            var doc = new window.jspdf.jsPDF('L', 'px', [w, h]);
            doc.addImage(img, 'JPEG', 0, 0, w, h);
            doc.save('sample-file.pdf');
        })
    })
缺点:
  • 生成的PDF文件由图片构成,内容无法拷贝,放大后不清晰
  • 分页打印位置无法控制
预览
2、方法二

jsPDF 直接基于Dom对象生成PDF 文件

jsPDF,支持添加页码

适用场景: 适合简单的页面布局,如常规的二维表,但复杂的报表样式定义Dom元素,使用起来就异常复杂了。

<script>
    function demoFromHTML() {
        var pdf = new jsPDF('p', 'pt', 'letter');
        // source can be HTML-formatted string, or a reference
        // to an actual DOM element from which the text will be scraped.
        source = $('#content')[0];
        // we support special element handlers. Register them with jQuery-style
        // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
        // There is no support for any other type of selectors
        // (class, of compound) at this time.
        specialElementHandlers = {
            // element with id of "bypass" - jQuery style selector
            '#bypassme': function (element, renderer) {
                // true = "handled elsewhere, bypass text extraction"
                return true
            }
        };
        margins = {
            top: 80,
            bottom: 60,
            left: 40,
            width: 522
        };
        // all coords and widths are in jsPDF instance's declared units
        // 'inches' in this case
        pdf.fromHTML(
        source, // HTML string or DOM elem ref.
        margins.left, // x coord
        margins.top, { // y coord
            'width': margins.width, // max width of content on PDF
            'elementHandlers': specialElementHandlers
        },
        function (dispose) {
            // dispose: object with X, Y of the last line add to the PDF
            //          this allow the insertion of new lines after html
            pdf.save('Test.pdf');
        }, margins);
    }
 </script>

缺点:

  • 多平台之间展示有差异,如手机端展示的Dom结构和电脑端布局有很大不同
  • 对中日韩文的字体支持不佳,会出现乱码
  • 布局在不同浏览器中有差异
3、方法三

使用 ActiveReportsJS直接在线设计布局,并直接生成PDF 文件

优点: 简单易用,可视化操作,所见即所得,代码量少,适用于多平台,保证PC端,Web端,手机端三端一致。

缺点:需要配相应字体,能够满足精准生成PDF 的需求。适用于保险业,金融业,检测业等对于PDF文件格式要求严格的的行业。

字体信息通常包含:

  • 字体名称: 字体ID 如 Arial, Calibri, 或 Times New Roman
  • 字体样式: 正常 或 斜体
  • 字体粗细: 较细,细体,正常,适中,粗体,较粗
  • 字体系列通常由多个字体组成,通常由单独的文件表示。

在报表Viewer中显示报表,将报表导出为PDF或托管报表设计器组件的应用程序应使用与为独立设计器应用程序创建的配置相同的配置。 最简单的方式是复制Fonts 文件夹和 fontsConfig.json 文件到项目的 assets 文件夹下面. 此文件夹因不同的前端框架而异。 示例如下:

RegisterFonts 方法是个异步函数,并会返回 Promise 对象。 也可以调用此方法的代码可以等待,直到返回Promise结果后,再在查看器组件中加载报表或导出报表。

{
    "name": "Montserrat",
    "weight": "900",
    "style": "italic",
    "source": "assets/Fonts/Montserrat/Montserrat-BlackItalic.ttf"
}  
<script src="https://cdn.grapecity.com/activereportsjs/2.latest/dist/ar-js-core.js"></script>
<script>
  GC.ActiveReports.Core.FontStore.registerFonts(
    "/resources/fontsConfig.json" // replace the URL with the actual one
  )
</script>  

var pageReport = new ARJS.PageReport();
            pageReport.load('Quotation.rdlx-json')
                .then(function() { return pageReport.run() })
                .then(function(pageDocument) { return PDF.exportDocument(pageDocument, settings) })
                .then(function(result) { result.download('arjs-pdf') });

相关文章

网友评论

      本文标题:前端pdf文件预览下载

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