Get x y coordinates from a pdf document on click - c#

I am trying to stamp a text in a pdf document. For this reason i need to be able to get the coordinates when I click in the pdf document. To stamp the text I am using itextsharp library. How can I get the x,y coordinates and the pdf page number.
this is my code for stamping:
public string formatPdf(string sourceFileName, string newFileName, string inputText, float xValue, float yValue)
{
using (Stream pdfStream = new FileStream(sourceFileName, FileMode.Open))
{
using (Stream newpdfStream = new FileStream(newFileName, FileMode.Create, FileAccess.ReadWrite))
{
PdfReader pdfReader = new PdfReader(pdfStream);
PdfStamper pdfStamper = new PdfStamper(pdfReader, newpdfStream);
PdfContentByte pdfContentByte = pdfStamper.GetOverContent(1);
BaseFont baseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
pdfContentByte.SetColorFill(BaseColor.RED);
pdfContentByte.SetFontAndSize(baseFont, 12);
pdfContentByte.BeginText();
pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_CENTER, inputText, xValue, yValue, 0);
pdfContentByte.EndText();
pdfStamper.Close();
}
}
return newFileName;
}

Related

ItextSharp return a corrupted file after editing existing pdf file

I am new to itextSharp. What I am doing is just editing the old file and instead of saving the new file on the server I just want it to download at the time. but unfortunately after editing the file and being downloaded, file display a message cannot open the file. It may be corrupted.
Here is my code.
public FileStreamResult export( int ? id)
{
string pathin = Server.MapPath(Url.Content("~/PDF/input.pdf"));
PdfReader reader = new PdfReader(pathin);
iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
//FileStream ms = new FileStream(pathout, FileMode.Create, FileAccess.Write);
var ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
writer.CloseStream = false;
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 18f);
// write the text in the pdf content
cb.BeginText();
string text = "this is text";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 500, 500, 0);
cb.EndText();
cb.BeginText();
text = "this is my post";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 600, 400, 0);
cb.EndText();
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
ms.Position = 0;
document.Close();
//ms.Close();
writer.Close();
reader.Close();
return File(ms, "application/pdf","test.pdf");
}
Any help will be really appreciated. :)
You change the position of the memory stream before closing the document:
ms.Position = 0;
document.Close();
As the trailer of the pdf in the result stream is written during the closing of the document, your change of stream position causes the pdf trailer to be written over the pdf header and the stream position thereafter to not be at the start.
Instead first close the document and the reader (the writer implicitly is closed by closing the document) and reset the stream position thereafter:
document.Close();
reader.Close();
ms.Position = 0;
return File(ms, "application/pdf","test.pdf");

Change pageSize of pdf before saving

I receive a pdf as a byte[]. When I save this binary as pdf, pageSize is too big. I want to change the pageSize in the code.
Currently I am trying it this way, based on what I found in other questions:
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using (MemoryStream stream = new MemoryStream(pdfAsBinary))
{
using (PdfReader reader = new PdfReader(pdfAsBinary))
{
using (Document doc = new Document(PageSize.A4))
{
PdfWriter writer = PdfWriter.GetInstance(doc, stream);
PdfImportedPage page = writer.GetImportedPage(reader, 1);
image = Image.GetInstance(page);
using (var pdfStream = new FileStream(tempPath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
{
PdfWriter pdfwriter = PdfWriter.GetInstance(doc, pdfStream);
doc.Open();
doc.SetPageSize(PageSize.A4);
image.ScalePercent(30f);
doc.Add(image);
doc.Close();
}
}
}
File.Copy(tempPath, pathToFile);
}
Or I tried using this method:
private static byte[] resizeToA4(byte[] inputDoc)
{
using (MemoryStream out = new MemoryStream())
{
using (PdfReader reader = new PdfReader(inputDoc))
{
using (Document doc = new Document(PageSize.A4))
{
PdfWriter writer = PdfWriter.GetInstance(doc, out);
}
}
return outPDF.ToArray();
}
None of the above is working and it feels like I'm overcomplicating things. How can I achieve my resizing of the pageSize to A4?
This method works for one-page-files.
public static void ScaleToA4self(byte[] pdfAsBinary, string locationOfPdfOut)
{
PdfReader reader = new PdfReader(pdfAsBinary);
Rectangle originalSize = reader.GetPageSize(1);
float originalHeight = originalSize.Height;
float originalWidth = originalSize.Width;
Rectangle newSize = PageSize.A4;
float newHeight = newSize.Height;
float newWidth = newSize.Width;
float scaleHeight = newHeight / originalHeight;
float scaleWidth = newWidth / originalWidth;
Document doc = new Document(newSize, 0, 0, 0, 0);
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(locationOfPdfOut, FileMode.Create));
doc.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, scaleWidth, 0, 0, scaleHeight, 0, 0);
doc.Close();
}

ItextSharp Add lines to PDF and convert into bytes without saving it.

I have a method that gets a pdf and adds's lines in that pdf and then creates a new pdf and saves it in a path that's given to it. Now I don't want to save that new file in a path instead I want to convert it into bytes and send in Emails how can I do that I tried a couple of methods but it all ways look for path says no path found here is the code.
protected void CreatePDF()
{
string Oldfile = #"C:\BlankPDFt.pdf"; // Gets the Template / The actualy agreement Letter
// (new FileInfo("C:/Documents/Docs.pdf")).Directory.Create(); // Go create this folder if it's not there
string NewFile = "C:/Documents/Docs.pdf";
PdfReader reader = new PdfReader(Oldfile);
iTextSharp.text.Rectangle Size = reader.GetPageSizeWithRotation(1);
Document document = new Document(Size);
FileStream fs = new FileStream(NewFile , FileMode.Create, FileAccess.Write); // This is where it all ways look for new file path
i dont want it to save instead convert to bytes but wont work.
PdfWriter weiter = PdfWriter.GetInstance(document, fs);
document.Open();
PdfContentByte cb = weiter.DirectContent;
PdfImportedPage page = weiter.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.BLACK);
cb.SetFontAndSize(bf, 12);
cb.BeginText();
// string Signatur = "Some texts"; // adds this text to that pdf
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Here", 335, 90, 0); // Insert the signature
cb.EndText();
}
The PdfWriter.GetInstance() method accepts an InputStream as its second argument. Instead of passing a FileStream you should pass it a MemoryStream.
MemoryStream memory_stream = new MemoryStream();
PdfWriter.GetInstance(document, memory_stream );
...
document.Close();
byte[] pdf_bytes = memory_stream.ToArray();

ItextSharp changing Userunit

If I change the userunit to 10 the size shown in acrobat is correct but when I import the pdf in CorelDrawX3 and X7 or in Rasterlink Pro5 the size get changed back to before Userunit was changed.
I have to change the userunit because the pdf is to big.
Here is my coding.
public void PDFUserUnit(string FileIn, string FileOut)
{
using (var doc = new Document(new Rectangle(10000f, 16000f)))
{
using (var fs = new FileStream(FileOut, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (var writer = PdfWriter.GetInstance(doc, fs))
{
iTextSharp.text.pdf.ByteBuffer.HIGH_PRECISION = true;
writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_6);
writer.Userunit = 10f;
doc.Open();
doc.NewPage();
PdfReader reader = new PdfReader(FileIn);
PdfContentByte canvas = writer.DirectContent;
PdfTemplate tmp = writer.GetImportedPage(reader, 1);
canvas.AddTemplate(tmp, 1f, 0, 0, 1f, 0, 0);
doc.Close();
}
}
}
}

itextsharp insert text in pdf file with C#

I want to insert text into a pdf file with iTextSharp using the code below. Many times it works right but other times it does not work.
FileStream pdfOutputFile = new FileStream(pdfTemplate, FileMode.Create);
PdfReader pdfReader = new PdfReader(pdffile, System.Text.Encoding.UTF8.GetBytes("ownerPassword"));
PdfStamper pdfStamper = null;
// pdfReader.Permissions = 1;
pdfStamper = new PdfStamper(pdfReader, pdfOutputFile);
AcroFields testForm = pdfStamper.AcroFields;
PdfContentByte pdfPageContents = pdfStamper.GetUnderContent(index + 1);
string[] formattext = printTxt.Split(new char[] { '\n' });
float lhight = 0;
float abxt = abx;
printTxt= "Hello word";
ft = new FormattedText(printTxt, Color.Black, "Arial", EncodingType.Winansi, true, 9);
Bitmap b = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(b);
Font f = new Font("Arial", 9);
pdfPageContents.BeginText();
BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, "ASCII", false);
pdfPageContents.SetFontAndSize(baseFont,20); // 40 point font
pdfPageContents.SetRGBColorFill(0, 0, 0);
float textAngle = 0;
pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, printTxt, abx+3, (float)aby + 12 + lhight, textAngle);
pdfPageContents.EndText();
The approach I use to write text on any Pdf file is that I create text fields using a software tool PDF Nitro Professional (You can use some other software to create these fields). Once done you can then use the following pattern of code to write text on those fields.
string pdfTemplate = filePath;
string newFile = outputFilePath;
PdfReader PDFWriter = new PdfReader(pdfTemplate);
PdfStamper pdfStampDocument = new PdfStamper(PDFWriter, new FileStream(newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStampDocument.AcroFields;
//For Text field
pdfFormFields.SetField("txtTextFieldName", "First Text");
//For Check Box Field
pdfFormFields.SetField("chkSomeCheckBox", "Yes");
PDFWriter.Close();
pdfStampDocument.Close();
Hope it helps.

Categories