动态调整大小/空格文本以适合div

时间:2023-01-27 17:33:52

I have a div with a fixed width, but the text inside (someones name) will vary. Is there a way of dynamically resizing/letter-spacing the text to fit perfectly in the div?

我有一个固定宽度的div,但里面的文字(someones name)会有所不同。有没有办法动态调整大小/字母间距文本以完全适合div?

However, I cannot use javascript as this script will be used in a HTML-PDF converter, which does not read javascript

但是,我不能使用javascript,因为这个脚本将用于HTML-PDF转换器,它不会读取javascript

text-align:justify won't work as if the text is too long for the div, it won't resize it. I find text-align:justify only works for paragraphs etc.

text-align:justify不会像div的文本太长一样工作,也不会调整它的大小。我发现text-align:justify仅适用于段落等。

The name cannot go onto two lines

这个名字不能分为两行

1 个解决方案

#1


0  

You need to use either:

你需要使用:

 Graphics graphics = this.CreateGraphics();
 SizeF textSize = graphics.MeasureString("How long am I?", this.Font);

or

要么

 Size textSize = TextRenderer.MeasureText("How long am I?", font);

TextRenderer is less accurate, but Graphics requires you to use a windows form - in your case you could have a form with a single textbox into which you place the text to be measured and then read it back, but TextRenderer is simpler.

TextRenderer不太准确,但Graphics要求您使用Windows窗体 - 在您的情况下,您可以使用单个文本框的表单放置要测量的文本然后将其读回,但TextRenderer更简单。

Using the above you could write a function that adjusted the font-size until the desired length was reached.

使用上面的内容,您可以编写一个调整字体大小的函数,直到达到所需的长度。

It would then be a case of setting the style on the text sent to the browser to reflect this font-size.

然后,将在发送到浏览器的文本上设置样式以反映此字体大小。

#1


0  

You need to use either:

你需要使用:

 Graphics graphics = this.CreateGraphics();
 SizeF textSize = graphics.MeasureString("How long am I?", this.Font);

or

要么

 Size textSize = TextRenderer.MeasureText("How long am I?", font);

TextRenderer is less accurate, but Graphics requires you to use a windows form - in your case you could have a form with a single textbox into which you place the text to be measured and then read it back, but TextRenderer is simpler.

TextRenderer不太准确,但Graphics要求您使用Windows窗体 - 在您的情况下,您可以使用单个文本框的表单放置要测量的文本然后将其读回,但TextRenderer更简单。

Using the above you could write a function that adjusted the font-size until the desired length was reached.

使用上面的内容,您可以编写一个调整字体大小的函数,直到达到所需的长度。

It would then be a case of setting the style on the text sent to the browser to reflect this font-size.

然后,将在发送到浏览器的文本上设置样式以反映此字体大小。