【问题标题】:Create a pdf of div and then print using javascript创建一个 div 的 pdf,然后使用 javascript 打印
【发布时间】:2021-05-19 19:44:33
【问题描述】:

我想创建一个 div 的 pdf,然后想打印该 pdf。

div里面有两个div 第一个 div 内容表 第二个 div 内容图片。

<div id="printableDiv">
   <div id="1st">
     <table>
     </table>
   </div>
   <div id="2nd">
    <img>
   </div>
</div>

我试过下面的代码

var imgData = canvas.toDataURL("image/jpeg", 1.0);
var pdf = new jsPDF('p', 'pt', 'a4');
var width = pdf.internal.pageSize.getWidth();
var height = pdf.internal.pageSize.getHeight();
pdf.addImage(imgData, 'JPG', 10, 10, width, height);
for (var i = 1; i <= totalPDFPages; i++) {
    pdf.addPage(PDF_Width, PDF_Height);
    pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height * i) + (top_left_margin * 4), canvas_image_width, canvas_image_height);
}

但这里它会创建一个 jpeg 图像,然后将其添加到 pdf,

我想将html内容直接添加到pdf中。

提前致谢

【问题讨论】:

  • 为什么不使用打印 css?
  • 你需要像jsPDF这样的库
  • @zer00ne 代码已经展示了jsPDF的用法。 OP 不知道fromHTML()
  • 这能回答你的问题吗? Export HTML table to pdf using jspdf

标签: javascript


【解决方案1】:

您可以在 google 或 stackoverflow 上搜索该问题,并且已经找到可以帮助您的答案。

例如,请参阅: Export HTML table to pdf using jspdf

这是一个带有工作示例的 jsfiddle 链接:

Export HTML table to PDF

要调用的相关函数是fromHTML(),希望不言自明。
来自 jsfiddle 的代码(在本例中,HTML 表的 id 为 customers):

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 = $('#customers')[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: 10,
        width: 700
    };
    // 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);
}

【讨论】:

  • 感谢@Peter Krebs 的回复,我尝试使用相同的方式,但没有得到预期的输出
  • 好的,所以用您尝试过的内容更新您的答案。您不应该期望它导出为 1:1 像素的完美 PDF 文件。我相信您可以通过简单的指令(宽度/高度/填充/边距/字体属性)使用@media print CSS 进行增强。
猜你喜欢
  • 2012-04-30
  • 2023-03-27
  • 2015-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-07
  • 1970-01-01
相关资源
最近更新 更多