I have the following code to apply a full page grid to an existing A4 pdf document. It works fine on pdfs I or others have produced with iText, but when I try to use on a PDF that has been created by me or others using the Win10 "Microsoft Print to PDF" printer driver the resulting grid does not fill the page, it stops short both on the right and bottom of page by a couple of cm.
The fltWidth and fltHeight is approx the same no matter which PDF I input, it is just ones produced with the MS Print to PDF that I have issue with, which are also A4.
pdfDoc.SetDefaultPageSize(PageSize.A4);
Document doc = new Document(pdfDoc, PageSize.A4);
doc.SetMargins(0f, 0f, 0f, 0f);
PdfDocument pdfDocData = new PdfDocument(new PdfReader(sourcePDF));
pdfDocData.CopyPagesTo(1, 1, pdfDoc);
iText.Kernel.Colors.Color colorGrey = new DeviceRgb(112, 112, 112);
float flt_02 = 0.2f;
PdfPage page = pdfDoc.GetFirstPage();
iText.Kernel.Geom.Rectangle pageSize = doc.GetPdfDocument().GetFirstPage().GetPageSize();
float fltWidth = pageSize.GetWidth();
float fltHeight = pageSize.GetHeight();
PdfCanvas canvas = new PdfCanvas(page);
for (int intIndex = 296; intIndex > 0; intIndex--)
{
float fltLineY = intIndex * 2.83464566929134f;
canvas.SetStrokeColor(colorGrey);
canvas.MoveTo(1, fltLineY);
canvas.LineTo(fltWidth, fltLineY);
canvas.SetLineWidth(flt_02);
canvas.ClosePathStroke();
}
for (int intIndex = 1; intIndex < 210; intIndex++)
{
float fltLineX = intIndex * 2.83464566929134f;
canvas.SetStrokeColor(colorGrey);
canvas.MoveTo(fltLineX, 1);
canvas.LineTo(fltLineX, fltHeight);
canvas.SetLineWidth(flt_02);
canvas.ClosePathStroke();
}
doc.Close();
pdfDoc.Close();```
When adding content to an existing PDF page, it can be necessary to wrap the existing content into an envelope that stores the original graphics state at the start and restores it at the end. Otherwise any changes applied by the existing content may influence your additions, e.g. by scaling it as in your case, by clipping it, by applying transparency, ...
With iText this can be enforced by using
new PdfCanvas(page, true)
instead of
new PdfCanvas(page)
(Actually the latter variant tries to determines whether adding such an envelope is necessary and sometimes applies it. In your case, though, it errs.)