Hi,
I tried the solution you provided, but still my PDF content is overlapping and the original PDF content is not visible where the textbox is added. Is there any way to make the original PDF content smaller so that original PDF content will be visible?
as I am using byte[] pdfContent, string annotationText
using (MemoryStream inputStream = new MemoryStream(pdfContent)) { PdfDocument inputDocument = PdfReader.Open(inputStream, PdfDocumentOpenMode.Import); PdfDocument outputDocument = new PdfDocument();
// Set up the font and initial parameters XFont font = new XFont("Arial", 12, XFontStyleEx.Regular); double lineHeight = 15; // Approximate height of one line of text
// Loop through each page of the input document for (int pageIndex = 0; pageIndex < inputDocument.PageCount; pageIndex++) { PdfPage inputPage = inputDocument.Pages[pageIndex]; PdfPage outputPage = outputDocument.AddPage(inputPage);
var mediaBox = inputPage.MediaBox; var pageRotation = inputPage.Rotate;
double pageWidth = mediaBox.Width; double pageHeight = mediaBox.Height;
if (pageRotation == 90 || pageRotation == 270) { pageWidth = mediaBox.Height; pageHeight = mediaBox.Width; }
double maxTextWidth = pageWidth - 10; // Keep padding of 5 points on each side
List<string> lines = new List<string>(); using (XGraphics gfxs = XGraphics.FromPdfPage(outputPage)) { string[] words = annotationText.Split(' '); StringBuilder currentLine = new StringBuilder();
foreach (string word in words) { string testLine = currentLine.Length == 0 ? word : currentLine + " " + word; double width = gfxs.MeasureString(testLine, font).Width;
if (width < maxTextWidth) { currentLine.Append(currentLine.Length == 0 ? word : " " + word); } else { lines.Add(currentLine.ToString()); currentLine.Clear(); currentLine.Append(word); } }
if (currentLine.Length > 0) { lines.Add(currentLine.ToString()); // Add the remaining text as a line } } double totalTextHeight = lines.Count * lineHeight + 10; // Add 10 for padding at top and bottom
outputPage.Height += XUnit.FromPoint(totalTextHeight);
XGraphics gfx = XGraphics.FromPdfPage(outputPage);
gfx.TranslateTransform(0, totalTextHeight);
XColor back = XColors.White; // Background color for the top space XSolidBrush brush = new XSolidBrush(back);
gfx.DrawRectangle(brush, new XRect(0, 0, pageWidth, totalTextHeight));
double textXPosition = 5; double textYPosition = 10; foreach (string line in lines) { gfx.DrawString(line, font, XBrushes.Black, new XPoint(textXPosition, textYPosition)); textYPosition += lineHeight; // Move down for the next line } }
using (MemoryStream stream = new MemoryStream()) { outputDocument.Save(stream); return stream.ToArray(); } }
I tried with ScaleFactor as well but it doesn't works for me.
|