【问题标题】:How to format PDF when converting HTML to PDF in Angular在Angular中将HTML转换为PDF时如何格式化PDF
【发布时间】:2021-05-22 22:56:33
【问题描述】:

我正在尝试使用 jspdf 和 html2canvas 将 HTML 转换为角度的 PDF。问题是我没有直接的方法来避免 PDF 中不需要的 HTML 元素。

HTML 代码

<button (click)="ConvertToHtml()">Generate PDF</button>
<div id="MainSegment">
  <div id="Div1">
    test 1
  </div>
  <div id="Unwanted">
    Unwanted stuff
  </div>
  <div id="Div2">
    test 2
  </div>
</div>

角度代码

import { Component, VERSION } from '@angular/core';
import * as jspdf from 'jspdf';
import html2canvas from 'html2canvas';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  ConvertToHtml() {
    var data = document.getElementById('MainSegment');
    html2canvas(data).then(canvas => {
      var imgWidth = 208;
      var imgHeight = (canvas.height * imgWidth) / canvas.width;
      const contentDataURL = canvas.toDataURL('image/png');
      let pdf = new jspdf('p', 'mm', 'a4');
      var position = 0;
      pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);
      pdf.save('sample.pdf');
    });
  }
}

在这里,我试图避免id="Unwanted" 元素。 我可能会隐藏(display:none)元素并在执行ConvertToHtml() 方法后再次显示它,但我想知道是否有办法只获取#Div1#Div2 元素并仅将这些元素转换为PDF。

【问题讨论】:

    标签: angular pdf


    【解决方案1】:

    您只需要添加以忽略您不想格式化为 PDF 的部分:

    data-html2canvas-ignore="true"
    

    例如:

     <div id="Unwanted" data-html2canvas-ignore="true">
    

    【讨论】:

      猜你喜欢
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      • 2019-03-05
      • 2012-01-12
      相关资源
      最近更新 更多