PDF.js scale PDF on fixed width

白昼怎懂夜的黑 提交于 2019-11-28 16:44:30

问题


I have a fixed box where I want to display my PDF's in rendered by PDF.js. As PDF.js documentation is not really accessible (spitting through their source files), I'd like to know whether it's possible to scale a rendered PDF on a fixed width. When I set as CSS: canvas { width: 600px; } for the canvas displaying the PDF, the PDF gets stretched, and the quality gets poor.


回答1:


I updated the example from the Pdf.js github http://jsbin.com/pdfjs-prevnext-v2/edit#html,live to scale properly to a fixed canvas width. See http://jsfiddle.net/RREv9/ for my code.

The important line is

var viewport = page.getViewport(canvas.width / page.getViewport(1.0).width);

because the expression canvas.width / page.getViewport(1.0).width gives us the appropriate scaling factor.

You should change the width of your canvas not with css but by the width attribute of the canvas. See Canvas width and height in HTML5




回答2:


To ensure that scaling works with all page sizes (Letter, A4, A5, etc.) you must take into account that the ratios between height and width with vary when page sizes change. For example a popular page sizes (in inches) are:

  • Letter: 8.5 x 11.. ratio of 0.772
  • A4: 8.27 × 11.7.. ratio of 0.706
  • A5: 5.83 × 8.27.. ratio of 0.704

You can calculate the correct scaling by considering both height and width and only scaling the amount that is smaller. This will ensure everything fits on your canvas. Additionally, should you change the width or height of your canvas, you will not break anything.

var unscaledViewport = page.getViewport(1);
var scale = Math.min((canvas.height / unscaledViewport.height), (canvas.width / unscaledViewport.width));
var viewport = page.getViewport(scale);


来源:https://stackoverflow.com/questions/13038146/pdf-js-scale-pdf-on-fixed-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!