PDFBOX 无法找到包含特定字符的像素数
PDFBOX unable to find number of pixels which contain a particular character
我正在使用 PDFBOX
创建 pdf。在 pdfbox 中是否有任何函数可以以像素为单位给出字体大小?例如字母 A
和 a
,将占用不同的打印空间。显然 A
比 a
需要更多的像素。我怎样才能找到应该占用一个字符或一个单词的像素数?
首先像素的概念有点模糊。
通常一个文件有一定的大小,例如inches/cm等
PDFBox 的 javadoc 显示 PDFont 有几种方法来确定字符串或字符的宽度。
例如,看看这些页面:
这些单位是 Em. Also see this page 的 1/1000。
完整示例:
float fontSize = 12;
String text = "a";
PDRectangle pageSize = PDRectangle.A4;
PDFont font = PDType1Font.HELVETICA_BOLD;
PDDocument doc = new PDDocument();
PDPage page = new PDPage(pageSize);
doc.addPage(page);
PDPageContentStream stream = new PDPageContentStream(doc,page);
stream.setFont( font, fontSize );
// charWidth is in points multiplied by 1000.
double charWidth = font.getStringWidth(text);
charWidth *= fontSize; // adjust for font-size.
stream.beginText();
stream.moveTextPositionByAmount(0,10);
float widthLeft = pageSize.getWidth();
widthLeft *= 1000.0; //due to charWidth being x1000.
while(widthLeft > charWidth){
stream.showText(text);
widthLeft -= charWidth;
}
stream.close();
// Save the results and ensure that the document is properly closed:
doc.save( "example.pdf");
doc.close();
我正在使用 PDFBOX
创建 pdf。在 pdfbox 中是否有任何函数可以以像素为单位给出字体大小?例如字母 A
和 a
,将占用不同的打印空间。显然 A
比 a
需要更多的像素。我怎样才能找到应该占用一个字符或一个单词的像素数?
首先像素的概念有点模糊。 通常一个文件有一定的大小,例如inches/cm等
PDFBox 的 javadoc 显示 PDFont 有几种方法来确定字符串或字符的宽度。 例如,看看这些页面:
这些单位是 Em. Also see this page 的 1/1000。
完整示例:
float fontSize = 12;
String text = "a";
PDRectangle pageSize = PDRectangle.A4;
PDFont font = PDType1Font.HELVETICA_BOLD;
PDDocument doc = new PDDocument();
PDPage page = new PDPage(pageSize);
doc.addPage(page);
PDPageContentStream stream = new PDPageContentStream(doc,page);
stream.setFont( font, fontSize );
// charWidth is in points multiplied by 1000.
double charWidth = font.getStringWidth(text);
charWidth *= fontSize; // adjust for font-size.
stream.beginText();
stream.moveTextPositionByAmount(0,10);
float widthLeft = pageSize.getWidth();
widthLeft *= 1000.0; //due to charWidth being x1000.
while(widthLeft > charWidth){
stream.showText(text);
widthLeft -= charWidth;
}
stream.close();
// Save the results and ensure that the document is properly closed:
doc.save( "example.pdf");
doc.close();