javascript - 如何使用 html2canvas 在 a4 大小的页面上调整 html 页面

标签 javascript html css html2canvas html-to-pdf

我已经工作了好几天来解决这个问题,但我无法解决这个问题,也许是因为缺乏对 html2canva 的了解,或者它不想被修复。我唯一想要的是将我的 pdf 放在 a4 大小的单页上,但它总是呈现在两页上。不知道我哪里出错了。请提出一些建议。
这是我的代码:

document.querySelector('#temp').contentEditable = true;

function createpdf() {
  let body = document.body
  let html = document.documentElement
  let height = Math.max(body.scrollHeight, body.offsetHeight,
    html.clientHeight, html.scrollHeight, html.offsetHeight)
  let element = document.querySelector('#temp')
  let heightCM = height / 35.35
  html2pdf(element, {
    margin: 1,
    filename: 'MyResume.pdf',
    image: {
      type: 'jpeg',
      quality: 4
    },
    html2canvas: {
      dpi: 400,
      letterRendering: true,
      scale: 3
    },
    jsPDF: {
      orientation: 'portrait',
      unit: 'cm',
      //   format: [heightCM, 50]
      format: 'a4'

    }
  }).save()
}
@page {
  size: A4;
  margin: 1cm;
}

/* p{
  font-size: 10px;
}
b{
  font-size: 10px;
}
li{
  font-size: 10px;
} */

body {
  margin: 0px;
}

.border {
  border-bottom: 1px solid red;
  padding-bottom: -4px;
}

.spacing {
  margin-top: -10px;
}

.paddingtop {
  padding-top: 15px;
  border-top: 1px solid red;
}

.paddingbottom {
  padding-bottom: -14px;
}

.right1 {
  padding-left: 15px;
  margin-left: 130px;
  padding-top: -53px;
}

.right2 {
  padding-left: 15px;
  margin-left: 130px;
  padding-top: -60px;
}

.right3 {
  padding-left: 15px;
  margin-left: 130px;
  padding-top: -52px;
}

.border1 {
  border-right: 1px solid red;
  margin-right: 596px;
  padding-bottom: 12px;
}

.border2 {
  border-right: 1px solid red;
  margin-right: 596px;
  padding-bottom: 0px;
}

.border3 {
  border-right: 1px solid red;
  margin-right: 596px;
  padding-bottom: 8px;
  margin-top: 18px;
}

.blankline {
  padding-bottom: 6px;
}

[contenteditable]:focus {
  outline: 0px solid transparent;
}


/* #pdf {
  width:650px;
  height:400px;
  position:absolute;
  left:29%;
  font-size:16px;
} */

#page {
  /* width: 794px; */
  /* height: 29.7cm; */
  width: 21cm;
  background-color: white;
  margin: 1% auto 1% auto;
  padding: 0.2cm 1.3cm 1cm 1.3cm;
  box-shadow: 0px 0px 20px 0px #000;
  line-height: 1.4em;
  text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>

<script src='https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.3/html2pdf.bundle.min.js'></script>

<script type="text/javascript" src="https://svc.webspellchecker.net/spellcheck31/wscbundle/wscbundle.js"></script>

<section id="page">
  <div id="temp">
    <h1>Nitin</h1>
    <p class="paddingbottom">
      <b>INFO</b>
    </p>
    <p class="paddingtop">
      <b>Address: </b> 44 Shirley Ave, West Chicago, IL 60185
    </p>
    <p class="spacing">
      <b>Phone:</b> 563-458-6942
    </p>
    <p class="blankline">
      <b>Email:</b> jmiller@gmail.com
    </p>
    <p class="paddingbottom">
      <b>PROFESSIONAL SUMMARY</b>
    </p>
    <p class="paddingtop blankline">
      A highly resourceful, flexible, innovative and enthusiastic project manager. Processing considerable experience of managing projects from beginning to end, defining the project plan, timeline, scope and executing the analysis before providing detailed
      recommendations. Having an impressive track record of delivering major operational improvement and of orchestrating people, schedules and resources for optimum productivity, efficiency and quality. Keen to find a challenging position with an ambitious
      company where I will able to continue to increase my project management skills.
    </p>
    <p class="border blankline">
      <b>EDUCATIONAL BACKGROUND</b>
    </p>
    <p>
      <b>Oct. 2015 - Apr. 2016</b>
      <br>
      <b>B.Tech (CSE)</b>
    </p>
    <p class="right1">
      Kurukshetra University
      <br> Seth Jai Prakash Mukand Lal Institute of Engineering and Technology, Raduar, District Yamunanagar
      <br> 79.48%
    </p>
    <p class="">
      <b>May 2017 - Jun. 2018</b>
      <br>
      <b>Senior Secondary Certificate</b>
    </p>
    <p class="right2">
      CBSE
      <br> S.D. Public School, Jagadhri
      <br> 92%
    </p>
    <p class="">
      <b>May 2017 - Jun. 2018</b>
      <br>
      <b>Matriculation</b>
    </p>
    <p class="right3">
      ICSE
      <br> St. Thomas School, Jagadhri
      <br> 84.6%
    </p>
    <p class="border blankline">
      <b>TECHNICAL SKILLS</b>
      <ul>
        <li>Beginner of - </li>
        <li>Proficient in - </li>
        <li class="blankline">Sufficient knowledge of - </li>
      </ul>
    </p>
    <p class="border blankline">
      <b>PROJECTS</b>
      <ul>
        <li class="blankline">
          <b>JARVIS - PERSONAL ASSISTANT - </b>
          <br>
          <p>(This project assists the end-user with day to day activities like searching queries in Google, finding locations, sending emails, playing songs, searching instagram profiles, opening webcam and many more.)</p>
        </li>
        <li class="blankline">
          <b>TRAVEL MANIA - </b>
          <br>
          <p>(It is a travelling website that enables users to plan their travel without any hassle. It is a team project in which I worked as a front-end developer.)</p>
        </li>
        <li class="blankline">
          <b>RESPRO - </b>
          <br>
          <p> (It is a website that provides a simple and efficient way of creating resume and cover letter for individuals. It is a team project in which I worked as a front-end developer.)</p>
        </li>
      </ul>
    </p>
    <p class="border blankline">
      <b>TRAININGS</b>
      <ul>
        <li class="blankline">
          <p>Attended 40 days training on “C++” at “WEBCOM Technologies, Yamunanagar” (Jun. 2019 to Jul. 2019).</p>
        </li>
        <li class="blankline">
          <p>Attended 21.5 hours training on "Python" from "Udemy" (Jul. 2020 to Aug. 2020).</p>
        </li>
      </ul>
    </p>
    <p class="border blankline">
      <b>SOFT SKILLS</b>
      <ul>
        <li>Teamwork</li>
        <li>Leadership</li>
        <li>Communication skills</li>
        <li>Time management</li>
      </ul>
    </p>
    <p class="border blankline">
      <b>ACHIEVEMENTS</b>
      <ul>
        <li>Won third position in FashP competition (2019).</li>
        <li>Won first position in Flower Arrangement competition (2012).</li>
        <li class="blankline">Won second position in Drawing competition (2012).</li>
      </ul>
    </p>
  </div>

</section>

<button id="Download" onclick="createpdf();">Download</button>

最佳答案

我解决了将 HTML 导出为 PDF 的问题。我为每个 div 创建 Canvas 。
也许这会对大家有所帮助。

private canvas: any = {
    monthYearCanvas: null,
    monthYearHeight: 0,
    periodCanvas: null,
    periodHeight: 0,
    assetCanvas: null,
    assetHeight: 0,
    badActorCanvas: null,
    badActorHeight: 0,
    eventCanvas: null,
    eventHeight: 0,
    tenLowOffCanvas: null,
    tenLowOffHeight: 0,
};

public triggerPrintReport(): void {
            if (
                this.isLoadingMonthYear ||
                this.isLoadingOnPeriod ||
                this.isLoadingOnAsset ||
                this.isLoadingOnBadActor ||
                this.isLoadingOnEvent ||
                this.isLoadingTenLowOff
            ) {
                alert('Wait for load data');
                return;
            }
    
            this.messageReport = true;
    
            const monthYearHTML = document.getElementById('htmlData-monthYear');
            const periodHTML = document.getElementById('htmlData-period');
            const assetHTML = document.getElementById('htmlData-asset');
            const badActorHTML = document.getElementById('htmlData-badActor');
            const eventHTML = document.getElementById('htmlData-event');
            const tenLowOffHTML = document.getElementById('htmlData-tenLowOff');
    
            this.createCanvasURL(monthYearHTML, 'monthYear');
            this.createCanvasURL(periodHTML, 'period');
            this.createCanvasURL(assetHTML, 'asset');
            this.createCanvasURL(badActorHTML, 'badActor');
            this.createCanvasURL(eventHTML, 'event');
            this.createCanvasURL(tenLowOffHTML, 'tenLowOff');
        }
    
        private createCanvasURL(element: any, type: string): void {
            html2canvas(element).then(canvas => {
                const width = 208;
    
                if (type === 'monthYear') {
                    this.canvas.monthYearHeight = canvas.height * width / canvas.width;
                    this.canvas.monthYearCanvas = canvas.toDataURL('image/png');
                } else if (type === 'period') {
                    this.canvas.periodHeight = canvas.height * width / canvas.width;
                    this.canvas.periodCanvas = canvas.toDataURL('image/png');
                } else if (type === 'asset') {
                    this.canvas.assetHeight = canvas.height * width / canvas.width;
                    this.canvas.assetCanvas = canvas.toDataURL('image/png');
                } else if (type === 'badActor') {
                    this.canvas.badActorHeight = canvas.height * width / canvas.width;
                    this.canvas.badActorCanvas = canvas.toDataURL('image/png');
                } else if (type === 'event') {
                    this.canvas.eventHeight = canvas.height * width / canvas.width;
                    this.canvas.eventCanvas = canvas.toDataURL('image/png');
                } else if (type === 'tenLowOff') {
                    this.canvas.tenLowOffHeight = canvas.height * width / canvas.width;
                    this.canvas.tenLowOffCanvas = canvas.toDataURL('image/png');
                }
    
                this.exportPDF();
            });
        }
    
        private exportPDF(): void {
            const PDF = new jsPDF('p', 'mm', 'a4');
    
            if (
                this.canvas.monthYearCanvas &&
                this.canvas.periodCanvas &&
                this.canvas.assetCanvas &&
                this.canvas.badActorCanvas &&
                this.canvas.badActorCanvas &&
                this.canvas.tenLowOffCanvas
            ) {
                PDF.addImage(this.canvas.monthYearCanvas, 'PNG', 1, 10, 208, this.canvas.monthYearHeight);
                PDF.addImage(this.canvas.periodCanvas, 'PNG', 1, 125, 208, this.canvas.periodHeight);
                PDF.addPage();
                PDF.addImage(this.canvas.assetCanvas, 'PNG', 1, 10, 208, this.canvas.assetHeight);
                PDF.addPage();
                PDF.addImage(this.canvas.badActorCanvas, 'PNG', 1, 10, 208, this.canvas.badActorHeight);
                PDF.addPage();
                PDF.addImage(this.canvas.eventCanvas, 'PNG', 1, 10, 208, this.canvas.eventHeight);
                PDF.addPage('l');
                PDF.addImage(this.canvas.tenLowOffCanvas, 'PNG', 1, 10, 208, this.canvas.tenLowOffHeight);
    
                this.messageReport = false;
    
                PDF.save('angular-demo.pdf');
            }
        }

关于javascript - 如何使用 html2canvas 在 a4 大小的页面上调整 html 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67867343/

相关文章:

javascript - html和javascript验证文本框中的密码

javascript - 如何在页面调整大小时保持 div 可见?

jquery - 使用 transform 平移节点,直到它到达其父节点的位置

javascript - Nodejs 数百个坐标之间的距离计算阻塞了我的服务器

javascript - Parent.navigate 仅适用于 IE。我有什么选择可以让它与其他浏览器一起使用?

javascript - replaceState() 与 pushState()

javascript - 使用 javascript 显示内联

javascript - 我如何强制 Karma 在每次测试之间重新启动浏览器?

javascript - 在 JavaScript 中使用带有分隔符的字符串进行 split

javascript - 图标克隆元素放在错误的位置