Pergunta

Quero redimensionar a fonte do estilo de um elemento de span até que o texto do span tenha 7,5 polegadas de largura quando impresso no papel, mas o JavaScript relata apenas a propriedade de largura de cliente do span em pixels.

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

E depois:

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

E depois:

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

Eu determinei experimentalmente em uma máquina que ela usa aproximadamente 90 dpi como fator de conversão, porque o código acima registra aproximadamente 675, pelo menos sob o Firefox 3.

Esse número não é necessariamente o mesmo sob diferentes navegador, impressora, tela, etc.

Então, como encontro o DPI que o navegador está usando? O que posso ligar para recuperar "90" no meu sistema?

Foi útil?

Solução

Eu acho que isso faz o que você quer. Mas eu concordo com os outros pôsteres, o HTML não é realmente adequado para esse tipo de coisa. De qualquer forma, espero que você ache isso útil.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
#container {width: 7in; border: solid 1px red;}
#span {display: table-cell; width: 1px; border: solid 1px blue; font-size: 12px;}
</style>
<script language="javascript" type="text/javascript">
function resizeText() {
  var container = document.getElementById("container");
    var span = document.getElementById("span");

    var containerWidth = container.clientWidth;
  var spanWidth = span.clientWidth; 
    var nAttempts = 900;
    var i=1;
    var font_size = 12;

    while ( spanWidth < containerWidth && i < nAttempts ) {
      span.style.fontSize = font_size+"px";

        spanWidth = span.clientWidth;

        font_size++;
      i++;
    }       
}
</script>
</head>

<body>
<div id="container">
<span id="span">test</span>
</div>
<a href="javascript:resizeText();">resize text</a>
</body>
</html>

Outras dicas

Para resumir:

Este não é um problema que você pode resolver usando HTML. Apesar de Propriedades de impressão CSS2, não há maneira definida ou esperada para os navegadores imprimirem as coisas.

Primeiramente, Um pixel (em CSS) não é necessário do mesmo tamanho que um pixel (na tela), portanto, o fato de um certo valor funcionar para você não significa que ele se traduza em outras configurações.

Em segundo lugar, os usuários podem alterar o tamanho do texto usando recursos como zoom de página, etc.

Em terceiro lugar, como não há como não existe uma maneira definida de definir páginas da web para fins de impressão, cada navegador faz isso de maneira diferente. Basta imprimir a visualização de algo no Firefox vs IE e ver a diferença.

Em quarto lugar, a impressão traz uma série de outras variáveis, como o DPI da impressora, o tamanho do papel. Além disso, a maioria dos drivers de impressora suporta a escala de usuário da saída Defina na caixa de diálogo de impressão que o navegador nunca vê.

Finalmente, provavelmente porque a impressão não é um objetivo do HTML, o 'mecanismo de impressão' do navegador da web é (em todos os navegadores que eu já vi) desconectadas do restante. Não há como o seu JavaScript 'conversar' com o mecanismo de impressão ou vice -versa; portanto, o "número do DPI que o navegador está usando para visualizações de impressão" não é exposto de forma alguma.

Eu recomendaria um arquivo PDF.

Eu determinei experimentalmente em uma máquina que ela usa aproximadamente 90 dpi como fator de conversão, porque o código acima registra aproximadamente 675, pelo menos sob o Firefox 3.

1) Isso é o mesmo em todas as máquinas/navegador?

Definitivamente não. Cada combinação de resolução / impressora / impressão / impressão será um pouco diferente. Há realmente uma maneira de saber qual será o tamanho da impressão, a menos que você esteja usando em em vez de pixels.

  1. Não
  2. Você não

Isso também é ainda mais complicado pelas configurações de resolução da tela.

Boa sorte.

A Web não é um bom meio para materiais impressos.

As made clear by the other answers, printing from the web is tricky business. It's unpredictable and sadly not all browsers and configuration react the same.

I would point you in this direction however:

You can attach a CSS to your document that is targeted specifically for printing like so

<link rel="stylesheet" type="text/css" href="print.css" media="print" />

That way you can format the printed output of your page in a separate style sheet and keep your regular stylesheet for displaying on screen. I've done this before with decent results -- although it required quite a bit of tweaking to ensure that the printed document comes out the way you want it.

An interesting article on the subject of printing from the web:

A List Apart - Going To Print

Some info from the W3C about CSS print profile:

W3C - CSS Print Profile

If you are generating content that is meant to look a specific way, you may want to look into a format that is meant to be printed, like PDF. HTML/CSS is meant to be adaptable to different configurations of screen size, resolution, color-depth, etc. It is not meant for saying a box should be exactly 7.5 inches wide.

Have you tried

@media print { #test { width: 7in; }}

This is a merged answer of what I've learned from the posts of Orion Edwards (especially the link to webkit.org) and Bill.

It seems the answer is actually always 96 DPI, although you're free to run the following (admittedly sloppy) code and I would love to hear if you get a different answer:

var bob = document.body.appendChild(document.createElement('div'));
bob.innerHTML = "<div id='jake' style='width:1in'>j</div>";
alert(document.getElementById('jake').clientWidth);

As the webkit.org article says, this number is fairly standard, and isn't affected by your printer or platform, because those use a different DPI.

Even if it isn't, using that above code you could find out the answer you need. Then you can use the DPI in your JavaScript, limiting the clientWidth like Bill did, combined with CSS that uses inches, to have something that prints out correctly so long as the user doesn't do any funky scaling like Orion Edwards mentioned--or at least, after that point, it's up to the user, who may be wanting to do something beyond what the programmer had in mind, like printing out on 11x17 paper something that the programmer designed to fit into 8.5x11, but still, it will "work right" for what the user wants even then.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top