Javascript 如何使用jsPDF设置图像以适应页面的宽度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36472094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set image to fit width of the page using jsPDF?
提问by sreeraj nyros
Is there any way to solve this? I tried to set width and height in mm. How can I set it to full-width?
有没有办法解决这个问题?我试图以毫米为单位设置宽度和高度。如何将其设置为全角?
回答by Purushoth
You can get the width and height of PDF document like below,
您可以获得如下所示的 PDF 文档的宽度和高度,
var doc = new jsPDF("p", "mm", "a4");
var width = doc.internal.pageSize.getWidth();
var height = doc.internal.pageSize.getHeight();
Then you can use this width and height for your image to fit the entire PDF document.
然后您可以使用此宽度和高度为您的图像适应整个 PDF 文档。
var imgData = 'data:image/jpeg;base64,/9j/4AAQSkZJ......';
doc.addImage(imgData, 'JPEG', 0, 0, width, height);
Make sure that your image has the same size (resolution) of the PDF document. Otherwise it will look distorted (stretched).
确保您的图像具有与 PDF 文档相同的大小(分辨率)。否则它看起来会变形(拉伸)。
If you want convert px
to mm
use this link http://www.endmemo.com/sconvert/millimeterpixel.php
如果您想转换px
为mm
使用此链接http://www.endmemo.com/sconvert/millimeterpixel.php
回答by Philip
If you need to get width 100%of PDF file and auto heightyou can use 'getImageProperties' property.
如果您需要获得PDF 文件的100% 宽度和自动高度,您可以使用“getImageProperties”属性。
html2canvas(input)
.then((canvas) => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF({
orientation: 'landscape',
});
const imgProps= pdf.getImageProperties(imgData);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
pdf.save('download.pdf');
});
回答by zerzevul
My answer deals with a more specific case of what you are asking but I think one could draw some ideas from this to apply more generally. Also, I would post this as a comment to Purushoth's answer (on which mine is based), if only I could.
我的回答涉及您所问问题的一个更具体的案例,但我认为人们可以从中汲取一些想法以更广泛地应用。另外,如果可以的话,我会将其发布为对Purushoth的回答(我的答案所基于的答案)的评论。
Ok, so my problem was how to fit a web page into the pdf document, without losing the aspect ratio. I used jsPDF in conjuction with html2canvas and I calculated the ratio from my div
's width and height. I applied that same ratio to the pdf document and the page fit perfectly onto the page without any distortion.
好的,所以我的问题是如何将网页放入 pdf 文档,而不会丢失纵横比。我将 jsPDF 与 html2canvas 结合使用,并根据我div
的宽度和高度计算了比率。我对 pdf 文档应用了相同的比例,页面完美地贴合在页面上,没有任何失真。
var divHeight = $('#div_id').height();
var divWidth = $('#div_id').width();
var ratio = divHeight / divWidth;
html2canvas(document.getElementById("div_id"), {
height: divHeight,
width: divWidth,
onrendered: function(canvas) {
var image = canvas.toDataURL("image/jpeg");
var doc = new jsPDF(); // using defaults: orientation=portrait, unit=mm, size=A4
var width = doc.internal.pageSize.getWidth();
var height = doc.internal.pageSize.getHeight();
height = ratio * width;
doc.addImage(image, 'JPEG', 0, 0, width-20, height-10);
doc.save('myPage.pdf'); //Download the rendered PDF.
}
});
回答by carbon1479
I discovered this while experimenting with html2canvas this morning. While this doesn't include provisions for printing multiple pages it does scale the image to page width and reframes the height in ratio to the adjusted width:
我今天早上在尝试 html2canvas 时发现了这一点。虽然这不包括打印多页的规定,但它确实将图像缩放到页面宽度,并根据调整后的宽度重新调整高度:
html2canvas(document.getElementById('testdiv')).then(function(canvas){
var wid: number
var hgt: number
var img = canvas.toDataURL("image/png", wid = canvas.width, hgt = canvas.height);
var hratio = hgt/wid
var doc = new jsPDF('p','pt','a4');
var width = doc.internal.pageSize.width;
var height = width * hratio
doc.addImage(img,'JPEG',20,20, width, height);
doc.save('Test.pdf');
});
回答by Emixam Ninka
回答by Ravi Guru
i faced same problem but i solve using this code
我遇到了同样的问题,但我使用此代码解决了
html2canvas(body,{
onrendered:function(canvas){
var pdf=new jsPDF("p", "mm", "a4");
var width = pdf.internal.pageSize.getWidth();
var height = pdf.internal.pageSize.getHeight();
pdf.addImage(canvas, 'JPEG', 0, 0,width,height);
pdf.save('test11.pdf');
}
})
回答by vohrahul
A better solution is to set the doc width/height using the aspect ratio of your image.
更好的解决方案是使用图像的纵横比设置文档宽度/高度。
var ExportModule = {
// Member method to convert pixels to mm.
pxTomm: function(px) {
return Math.floor(px / $('#my_mm').height());
},
ExportToPDF: function() {
var myCanvas = document.getElementById("exportToPDF");
html2canvas(myCanvas, {
onrendered: function(canvas) {
var imgData = canvas.toDataURL(
'image/jpeg', 1.0);
//Get the original size of canvas/image
var img_w = canvas.width;
var img_h = canvas.height;
//Convert to mm
var doc_w = ExportModule.pxTomm(img_w);
var doc_h = ExportModule.pxTomm(img_h);
//Set doc size
var doc = new jsPDF('l', 'mm', [doc_w, doc_h]);
//set image height similar to doc size
doc.addImage(imgData, 'JPG', 0, 0, doc_w, doc_h);
var currentTime = new Date();
doc.save('Dashboard_' + currentTime + '.pdf');
}
});
},
}
<script src="Scripts/html2canvas.js"></script>
<script src="Scripts/jsPDF/jsPDF.js"></script>
<script src="Scripts/jsPDF/plugins/canvas.js"></script>
<script src="Scripts/jsPDF/plugins/addimage.js"></script>
<script src="Scripts/jsPDF/plugins/fileSaver.js"></script>
<div id="my_mm" style="height: 1mm; display: none"></div>
<div id="exportToPDF">
Your html here.
</div>
<button id="export_btn" onclick="ExportModule.ExportToPDF();">Export</button>
回答by Weihui Guo
It's easy to fit the page if you only have one image. The more challenge task is to fit images with various sizes to a pdf file. The key to archive that is to calculate the aspect ratio of the image and relative width/height ratio of the page. The following code is what I used to convert multiple images online to a PDF file. It will rotate the image(s) based on the orientation of the images/page and set proper margin. My project use images with online src. You should be able to modify to suit your needs.
如果您只有一张图片,很容易适应页面。更具挑战性的任务是将各种尺寸的图像放入 pdf 文件。存档的关键是计算图片的纵横比和页面的相对宽高比。以下代码是我用来在线将多个图像转换为 PDF 文件的代码。它将根据图像/页面的方向旋转图像并设置适当的边距。我的项目使用带有在线 src 的图像。您应该能够进行修改以满足您的需求。
As for image rotation, if you see a blank page after rotation, it could simply be that the image is out of bounds. See this answerfor details.
至于图像旋转,如果您在旋转后看到一个空白页面,则可能只是图像越界。有关详细信息,请参阅此答案。
function exportPdf(urls) {
let pdf = new jsPDF('l', 'mm', 'a4');
const pageWidth = pdf.internal.pageSize.getWidth();
const pageHeight = pdf.internal.pageSize.getHeight();
const pageRatio = pageWidth / pageHeight;
for (let i = 0; i < urls.length; i++) {
let img = new Image();
img.src = urls[i];
img.onload = function () {
const imgWidth = this.width;
const imgHeight = this.height;
const imgRatio = imgWidth / imgHeight;
if (i > 0) { pdf.addPage(); }
pdf.setPage(i + 1);
if (imgRatio >= 1) {
const wc = imgWidth / pageWidth;
if (imgRatio >= pageRatio) {
pdf.addImage(img, 'JPEG', 0, (pageHeight - imgHeight / wc) / 2, pageWidth, imgHeight / wc, null, 'NONE');
}
else {
const pi = pageRatio / imgRatio;
pdf.addImage(img, 'JPEG', (pageWidth - pageWidth / pi) / 2, 0, pageWidth / pi, (imgHeight / pi) / wc, null, 'NONE');
}
}
else {
const wc = imgWidth / pageHeight;
if (1 / imgRatio > pageRatio) {
const ip = (1 / imgRatio) / pageRatio;
const margin = (pageHeight - ((imgHeight / ip) / wc)) / 4;
pdf.addImage(img, 'JPEG', (pageWidth - (imgHeight / ip) / wc) / 2, -(((imgHeight / ip) / wc) + margin), pageHeight / ip, (imgHeight / ip) / wc, null, 'NONE', -90);
}
else {
pdf.addImage(img, 'JPEG', (pageWidth - imgHeight / wc) / 2, -(imgHeight / wc), pageHeight, imgHeight / wc, null, 'NONE', -90);
}
}
if (i == urls.length - 1) {
pdf.save('Photo.pdf');
}
}
}
}
If this is a bit hard to follow, you can also use
.addPage([imgWidth, imgHeight])
, which is more straightforward. The downside of this method is that the first page is fixed bynew jsPDF()
. See this answerfor details.
如果这有点难以理解,您也可以使用
.addPage([imgWidth, imgHeight])
,这更直接。这种方法的缺点是第一页由new jsPDF()
. 有关详细信息,请参阅此答案。
回答by thephper
If you want a dynamic sized imageto automatically fill the page as much as possible and still keep the image width/height-ratio, you could do as follows:
如果您希望动态大小的图像尽可能多地自动填充页面并仍然保持图像的宽度/高度比,您可以执行以下操作:
let width = doc.internal.pageSize.getWidth()
let height = doc.internal.pageSize.getHeight()
let widthRatio = width / canvas.width
let heightRatio = height / canvas.height
let ratio = widthRatio > heightRatio ? heightRatio : widthRatio
doc.addImage(
canvas.toDataURL('image/jpeg', 1.0),
'JPEG',
0,
0,
canvas.width * ratio,
canvas.height * ratio,
)