问题
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
回答1:
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).
来源:https://stackoverflow.com/questions/24861632/how-to-increase-the-accuracy-of-measurements-in-itextsharp