I wan't write a paragraph in the pdf file so that the top left corner of the paragraph is exactly positioned at the top left corner of the page 100,100.The code:
var targetPdfPath = "100x100.pdf";
using (PdfDocument pdfDoc = new PdfDocument(new PdfWriter(targetPdfPath)))
{
Document document = new Document(pdfDoc);
var page = pdfDoc.AddNewPage(PageSize.A4);
Paragraph paragraph = new Paragraph("Must be at (100,100)");
PdfFont FontHELVETICA = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
paragraph.SetFontSize(20f);
var pageHeight = PageSize.A4.GetHeight();
PdfCanvas pdfCanvas = new PdfCanvas(page);
var rectHeight = 200f;
var rectWidth = 200f;
pdfCanvas.SetLineWidth(0.5f);
pdfCanvas.Rectangle(100, pageHeight - 100 - rectHeight, 200, 200);//It is easy to place the rectangle in the position of (100,100)pt
pdfCanvas.Stroke();
Canvas canvas = new Canvas(pdfCanvas, PageSize.A4);
var paragraphHeight = 0f;//How to get it??
paragraph.SetFixedPosition(100, pageHeight - 100f - paragraphHeight, 200);//It is difficult to place paragraphs in the position of (100,100)pt
canvas.Add(paragraph);
}
I can't get the right result no matter how much I test.How can I do?
100x100.pdf
You already use a Canvas
. How about setting the Canvas
area to have its upper left corner at (100, 100) and let iText do the layout work:
Canvas canvas = new Canvas(pdfCanvas, PageSize.A4.ApplyMargins(100, 0, 0, 100, false));
canvas.Add(paragraph);
You may have to set the paragraph margin and padding to 0 before adding:
paragraph.SetMarginTop(0);
paragraph.SetPaddingTop(0);
(PositionParagraph test PositionParagraphAt100_100
)
(I don't have Adobe Illustrator, so I cannot check whether this conforms to Illustrator's idea of the top left corner of the text.)