我正在尝试编写一些将PDF的第一页转换为PNG缩略图的代码。我在stackoverflow和web上的其他地方找到了几个例子,这似乎是一件很简单的事情,但是我无法让它发挥作用。
我有一个看起来像这样的HTML文件
<!DOCTYPE html>
<html>
<head>
<title>JR PDF test</title>
</head>
<body>
<script type="text/javascript" src="/build/pdf.js"></script>
<script type="text/javascript" src="jr-pdf.js"></script>
<script type="text/javascript" src="canvas2image.js"></script>
</body>
<div id="pdf-main-container">
<a id="download-image" href="#">Download PNG</a>
</div>
</div>
</html>
<canvas id="the-canvas"></canvas>
和jr-pdf.js看起来像这样
// URL of PDF document
var url = "REGLEMENT_FOR_RALLY_2012.pdf";
// Asynchronous download PDF
PDFJS.getDocument(url)
.then(function(pdf) {
return pdf.getPage(1);
})
.then(function(page) {
// Set scale (zoom) level
var scale = 1.5;
// Get viewport (dimensions)
var viewport = page.getViewport(scale);
// Get canvas#the-canvas
var canvas = document.getElementById('the-canvas');
// Fetch canvas' 2d context
var context = canvas.getContext('2d');
// Set dimensions to Canvas
canvas.height = viewport.height;
canvas.width = viewport.width;
// Prepare object needed by render method
var renderContext = {
canvasContext: context,
viewport: viewport
};
// Render PDF page
page.render(renderContext);
// JR experiments
console.log('hej');
url = canvas.toDataURL();
downloadButton = document.getElementById('download-image');
downloadButton.setAttribute('download', 'jr.png');
downloadButton.setAttribute('href', url);
});
PDF文件的第一页正确呈现到屏幕上,并生成jr.png文件。当我查看PNG文件时,标题似乎正确,但当我尝试使用图像查看器查看文件时,它是空的(实际上它显示为透明)。
所以我猜这些行是错误的:
url = canvas.toDataURL();
downloadButton = document.getElementById('download-image');
downloadButton.setAttribute('download', 'jr.png');
downloadButton.setAttribute('href', url);
有关如何制作正确的PNG文件的任何建议吗?
答案 0 :(得分:2)
page.render
是异步函数 - 你需要等到它完成绘画
var renderTask = page.render(renderContext);
renderTask.promise.then(function () {
// use canvas now
var url = canvas.toDataURL();
var downloadButton = document.getElementById('download-image');
downloadButton.setAttribute('download', 'jr.png');
downloadButton.setAttribute('href', url);
});