Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert pixels to printed inches in JavaScript?

I want to resize the font of a SPAN element's style until it the SPAN's text is 7.5 inches wide when printed out on paper, but JavaScript only reports the SPAN's clientWidth property in pixels.

<span id="test">123456</span>

And then:

#test {
  font-size:1.2in; /* adjust this for yourself until printout measures 7.5in wide */
}

And then:

console.log(document.getElementById('test').clientWidth);

I've determined experimentally on one machine that it uses approximately 90 DPI as a conversion factor, because the above code logs approximately 675, at least under Firefox 3.

This number is not necessarily the same under different browser, printer, screen, etc. configurations.

So, how do I find the DPI the browser is using? What can I call to get back "90" on my system?

like image 875
Kev Avatar asked Dec 07 '22 09:12

Kev


1 Answers

To summarize:

This is not a problem you can solve using HTML. Apart from the CSS2 print properties, there is no defined or expected way for browsers to print things.

Firstly, A pixel (in CSS) is not neccessarily the same size as a pixel (on your screen), so the fact that a certain value works for you doesn't mean it will translate to other setups.

Secondly, users can change the text size using features like page zoom, etc.

Thirdly, because there are is no defined way of how to lay out web pages for print purposes, each browser does it differently. Just print preview something in firefox vs IE and see the difference.

Fourthly, printing brings in a whole slew of other variables, such as the DPI of the printer, the paper size. Additionally, most printer drivers support user-scaling of the output set in the print dialog which the browser never sees.

Finally, most likely because printing is not a goal of HTML, the 'print engine' of the web browser is (in all browsers I've seen anyway) disconnected from the rest of it. There is no way for your javascript to 'talk' to the print engine, or vice versa, so the "DPI number the browser is using for print previews" is not exposed in any way.

I'd recommend a PDF file.

like image 195
Orion Edwards Avatar answered Mar 08 '23 13:03

Orion Edwards