Adding PDF template page to new inserted page. using itextsharp - c#

I have created one pdf file that i want to use as template page (contain header and border), so when i add new page to existing pdf it automatically set header and border to newly added page.
I am using ITextSharp PDF library.
I have try using PdfImportedPage as below but it's not working:
PdfReader templateFile;
templateFile = new PdfReader("D:\\templatefile.pdf");
PdfImportedPage template_page;
var fileStream1 = new FileStream("D:\\temp.pdf", FileMode.Create, FileAccess.Write);
var stamper1 = new PdfStamper(templateFile, fileStream1);
template_page = stamper1.GetImportedPage(templateFile, 1);
// now i want to add this template_page to existing pdf at specific position
//this is the file(existingpdf.pdf) in which i want to add template_page create above using stamper
var bytes = File.ReadAllBytes("D:\\existingpdf.pdf");
var reader = new PdfReader(bytes);
var numberofPages = reader.NumberOfPages;
var fileStream = new FileStream("D:\\result.pdf", FileMode.Create, FileAccess.Write);
//stamper of result pdf
var stamper = new PdfStamper(reader, fileStream);
stamper.InsertPage(numberofPages + 1, templateFile.GetPageSize(1));
//below code i have tried to add template but its not working in result pdf
stamper.GetUnderContent(2).AddTemplate(template_page, 0, 0);
stamper.Close();

Related

itext7 CopyPagesTo not opening PDF

I am trying to add a Cover Page PDF file to another PDF file. I am using CopyPagesTo method. CoverPageFilePath will go before any pages in the pdfDocumentFile. I then need to rewrite that new file to the same location. When I run the code and open the new pdf file I get an error about it being damaged.
public static void iText7MergePDF()
{
byte[] modifiedPdfInBytes = null;
string pdfCoverPageFilePath = #"PathtoCoverPage\Cover Page.pdf";
PdfDocument pdfDocumentCover = new PdfDocument(new iText.Kernel.Pdf.PdfReader(pdfCoverPageFilePath));
string pdfDocumentFile =#"PathtoFullDocument.pdf";
var buffer = File.ReadAllBytes(pdfDocumentFile);
using (var originalPdfStream = new MemoryStream(buffer))
using (var modifiedPdfStream = new MemoryStream())
{
var pdfReader = new iText.Kernel.Pdf.PdfReader(originalPdfStream);
var pdfDocument = new PdfDocument(pdfReader, new PdfWriter(modifiedPdfStream));
int numberOfPages = pdfDocumentCover.GetNumberOfPages();
pdfDocumentCover.CopyPagesTo(1, numberOfPages, pdfDocument);
modifiedPdfInBytes = modifiedPdfStream.ToArray();
pdfDocument.Close();
}
System.IO.File.WriteAllBytes(pdfGL, modifiedPdfInBytes);
}
Whenever you have some other type, like a StreamWriter, or here a PdfWriter writing to a Stream, it may not write all the data to the Stream immediately.
Here you Close the pdfDocument for all the data to be written to the MemoryStream.
ie this
modifiedPdfInBytes = modifiedPdfStream.ToArray();
pdfDocument.Close();
Should be
pdfDocument.Close();
modifiedPdfInBytes = modifiedPdfStream.ToArray();

ItextSharp Find text in pdf and highlight it

I am working on PDF functionality, I want to search text in PDF and highlight the found text in the PDF. For that I am using iTextsharp.
I did not get any solution yet, please provide me with a solution.
I have written following code;
public ActionResult Index1()
{
string outputFile = #"D:\Test.pdf";
using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (Document doc = new Document(PageSize.LETTER))
{
using (PdfWriter w = PdfWriter.GetInstance(doc, fs))
{
doc.Open();
doc.Add(new Paragraph("This is a test and sample pdf for test and wait for it"));
doc.Close();
}
}
}
List<int> pages = new List<int>();
PdfReader pdfReader = new PdfReader(outputFile);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentPageText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
if (currentPageText.Contains("test"))
{
pages.Add(page);
}
}
pdfReader.Close();
//Create a new file from our test file with highlighting
string highLightFile = #"D:\Test1.pdf";
//Bind a reader and stamper to our test PDF
PdfReader reader = new PdfReader(outputFile);
using (FileStream fs = new FileStream(highLightFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (PdfStamper stamper = new PdfStamper(reader, fs))
{
iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(60.6755f, 749.172f, 94.0195f, 735.3f);
float[] quad = { rect.Left, rect.Bottom, rect.Right, rect.Bottom, rect.Left, rect.Top, rect.Right, rect.Top };
PdfAnnotation highlight = PdfAnnotation.CreateMarkup(stamper.Writer, rect, null, PdfAnnotation.MARKUP_HIGHLIGHT, quad);
//Set the color
highlight.Color = BaseColor.YELLOW;
//Add the annotation
stamper.AddAnnotation(highlight, 1);
}
}
return View();
}
Above code creates one PDF (test1.pdf)
And in another PDF it highlights some text with hard-coded coordinates, I need to find the coordinates of some text in the PDF.
But I could not find the coordinates of the text I'm looking for.
In iText7, we have implemented this functionality.
It can be found in the class RegexBasedLocationExtractionStrategy.
I suggest you have a look to see how it was done, since this functionality was not backported to iText5.

Not able to fill multiple rows in xfa pdf with FillXfaForm() using itextsharp

I was trying with below code to fill multiple rows in xfa pdf using FillXfaForm() method in C#.net. Anyone please guide me what is wrong on this code. We are using itexsharp.dll version 5.5.4.0.
public void manipulatePdf()
{
using (FileStream existingPdf = new FileStream "existingPdf.pdf",FileMode.Open))
using (FileStream sourceXml = new FileStream("sourceXml.xml", FileMode.Open))
using (FileStream newPdf = new FileStream("mymergedPdf.pdf", FileMode.Create))
{
// Open existing PDF
PdfReader pdfReader = new PdfReader(existingPdf);
// PdfStamper, which will create
PdfStamper stamper = new PdfStamper(pdfReader, newPdf);
AcroFields form = stamper.AcroFields;
XfaForm xfa = form.Xfa;
xfa.FillXfaForm(sourceXml);
stamper.Close();
pdfReader.Close();
}
}

add a new page to pdf document c#

I need to add another page in a pdf file created using below code. the next page should also use the same template placed at path:
HostingEnvironment.MapPath("~/Content/InvoiceTemplate/invoiceTemplate.pdf")
I am using itextsharp library to create documents. Below is the code used to generate pdf.
public static void WriteInTemplate(List<Models.Statement> statementList)
{
string invoiceNumber = statementList.FirstOrDefault().Invoice.ToString().Trim();
string month = null;
string day = null;
string year = null;
PdfReader pdfReader = new PdfReader(HostingEnvironment.MapPath("~/Content/InvoiceTemplate/invoiceTemplate.pdf"));
FileStream fileStream = new FileStream(HostingEnvironment.MapPath("~/Content/reports/" + invoiceNumber + ".pdf"), FileMode.Create);
PdfStamper pdfStamper = new PdfStamper(pdfReader, fileStream);
AcroFields pdfFields = pdfStamper.AcroFields;
pdfFields.SetField("BillToCompany", statementList.FirstOrDefault().BillToCompany.ToString().Trim().ToUpper());
pdfFields.SetField("BillToContact", statementList.FirstOrDefault().BillToContact.ToString().Trim().ToUpper());
pdfFields.SetField("CustomerId", statementList.FirstOrDefault().Customer_ID);
pdfFields.SetField("InvoiceNumber", statementList.FirstOrDefault().Invoice.ToString().Trim());
pdfFields.SetField("JobNumber", statementList.FirstOrDefault().JobNumber.ToString().Trim());
pdfFields.SetField("Caller", statementList.FirstOrDefault().Caller.ToString().Trim());
pdfStamper.FormFlattening = true; // generate a flat PDF
pdfStamper.Close();
pdfReader.Close();
}
You need to create a PDFDocument and then merge the files that you create into it. There is a very good example of this in this link: Merge PDFs using ITextSharp.

iTextSharp - Adding a vertical textbox

Does anyone know if it's possible to add a vertical textbox to a PDF document using itextsharp.
I have tried rotating the page first
PdfDictionary pDict = reader.GetPageN(1);
pDict.Put(PdfName.ROTATE, new PdfNumber(90));
AddTextBox(stamper, ...........)
// Rotate back
but this just adds the textbox horizontally, do I need to get another instance of stamper after the rotation?
When you create the TextField set its Rotation property:
PdfReader reader = new PdfReader(file1);
using (FileStream fs = new FileStream(file2, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (PdfStamper stamper = new PdfStamper(reader, fs))
{
TextField tf = new TextField(stamper.Writer, new iTextSharp.text.Rectangle(0, 0, 100, 300), "Vertical");
//Change the orientation of the text
tf.Rotation = 90;
stamper.AddAnnotation(tf.GetTextField(), 1);
}
}

Categories

Resources