如何提高iTextSharp中的测量精度? [英] How to increase the accuracy of measurements in iTextSharp?
问题描述
我想将pdf调整为特定大小,但是当我使用缩放比例时,它会失去精度,因为浮点数会将值四舍五入.有没有一种方法可以调整给定宽度和高度的pdf大小?到目前为止,这是我尝试过的:
I want to resize a pdf to a specific size, but when I use scaling it loses accuracy because a float rounds the value. Is there a way that I can resize a pdf with a given width and height? This is what I've tried so far:
public void PDFScalingTest11(string FileIn, string FileOut)
{
// The following code opens a pdf and place it 20 times on a new pdf page
// I want to resize the pdf before adding it
int iQuantity = 20;
int iCol = 3;
int iRow = 0;
float fTileSpacing = 0;
float fPrintWidth = 1200f; // Page Width
float fPrintHeight = 4158f; // PageHeight
float fWidth = 400f; // output size
float fHeight = 594f;
float fPdfWidth = 210f;// current pdf size
float fPdfHeight = 297f;
float fScalingWidth = fWidth / fPdfWidth; // scaling (this value should be (1.904761904761905) but is rounded to (1.90476191)
float fScalingHeight = fHeight / fPdfHeight; // this value is correct
fPrintWidth = iTextSharp.text.Utilities.MillimetersToPoints(fPrintWidth); // change mm to points
fPrintHeight = iTextSharp.text.Utilities.MillimetersToPoints(fPrintHeight);
fWidth = iTextSharp.text.Utilities.MillimetersToPoints(fWidth);
fHeight = iTextSharp.text.Utilities.MillimetersToPoints(fHeight);
fTileSpacing = iTextSharp.text.Utilities.MillimetersToPoints(fTileSpacing);
float x = 0;
float y = (((fHeight + fTileSpacing) * iRow) - (fTileSpacing + fHeight));
using (var doc = new Document(new Rectangle(fPrintWidth, fPrintHeight)))
{
using (var fs = new FileStream(FileOut, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (var writer = PdfWriter.GetInstance(doc, fs))
{
doc.Open();
doc.NewPage();
iDraw = 0;
PdfReader reader = new PdfReader(FileIn);
PdfContentByte canvas = writer.DirectContent;
PdfTemplate tmp = writer.GetImportedPage(reader, 1);
for (int i = 0; i < iQuantity; i++)
{
canvas.AddTemplate(tmp, fScalingWidth, 0, 0, fScalingHeight, x, y);
x += fTileSpacing + fWidth;
iDraw++;
if (iDraw == iCol)
{
y -= fHeight + fTileSpacing;
x = 0;
iDraw = 0;
}
}
doc.Close();
}
}
}
System.Diagnostics.Process.Start(FileOut);
}
// The width of each pdf added to the new pdf page is 399mm instead of 400
推荐答案
ByteBuffer
类具有一个名为HIGH_PRECISION
的公共静态变量.默认情况下,它设置为false
.您可以将其设置为true
,以便在四舍五入数字时获得小数点后6位:
The ByteBuffer
class has a public static variable named HIGH_PRECISION
. By default, it is set to false
. You can set it to true
so that you get 6 decimal places when rounding a number:
iTextSharp.text.pdf.ByteBuffer.HIGH_PRECISION = true;
这会降低您的性能(但也许您几乎不会注意到),并且生成的文件将具有更多的字节(但测量结果会更准确).
That will cost you some performance (but maybe you'll hardly notice that) and the resulting file will have more bytes (but measurements will be more accurate).
这篇关于如何提高iTextSharp中的测量精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!