Add background to every page in PDF using iText 7 - c#

I have PDF file with one page and I want to use it like a background for all my pages in second PDF file with some information. I've tried to do it with CopyPagesTo but it just copy PDF every second page.
private void ApplyBackground(string sourceFilename, string backgroundPdf, int pageNumber) {
PdfDocument srcDocument = new PdfDocument(new PdfReader(sourceFilename));
PdfDocument bgDocument = new PdfDocument(new PdfReader(backgroundPdf));
PdfDocument destDocument = new PdfDocument(new PdfWriter(#"C:\Desktop\result.pdf").SetSmartMode(true));
int pagesCount = srcDocument.GetNumberOfPages();
for (int i = 1; i <= pagesCount; i++) {
srcDocument.CopyPagesTo(i, i, destDocument);
bgDocument.CopyPagesTo(1, 1, destDocument);
}
srcDocument.Close();
bgDocument.Close();
destDocument.Close();
}
Is it possible to use one PDF file like a background and put it into other PDF file every page behind text.

Here is the iText 7 code. Please note that it assumes equal page sizes for the page with the background and the pages of the document being processed.
PdfDocument backgroundDocument = new PdfDocument(new PdfReader(#"path/to/background_doc.pdf"));
PdfDocument pdfDocument = new PdfDocument(new PdfReader(#"path/to/source.pdf"),
new PdfWriter(#"path/to/target.pdf"));
PdfFormXObject backgroundXObject = backgroundDocument.GetPage(1).CopyAsFormXObject(pdfDocument);
for (int i = 1; i <= pdfDocument.GetNumberOfPages(); i++) {
PdfPage page = pdfDocument.GetPage(i);
PdfStream stream = page.NewContentStreamBefore();
new PdfCanvas(stream, page.GetResources(), pdfDocument).AddXObject(backgroundXObject, 0, 0);
}
pdfDocument.Close();
backgroundDocument.Close();

Based on my understanding you are looking for below solution. If I missed something then please let me know.
Create reader for Original PDF for which you want to create background.
Create PDF reader for background PDF
Create PDF stamper where you want to generate final PDF.
Get background using GetImportedPage method for Stamper.
Loop on all pages of original PDF pages and add background.
Below is the code:
static void CreatePdfwithBackGround(string originalPdf, string backgroundPdf, string destPdf)
{
PdfReader originalPdfReader = new PdfReader(originalPdf);
PdfReader backgroundPdfReader = new PdfReader(backgroundPdf);
// Create the stamper for Destination pdf
PdfStamper stamper = new PdfStamper(originalPdfReader, new FileStream(destPdf, FileMode.Create));
// Add the backgroundPdf to each page of original PDF
PdfImportedPage page = stamper.GetImportedPage(backgroundPdfReader, 1);
int pageCount = originalPdfReader.NumberOfPages;
PdfContentByte background;
for (int i = 1; i <= pageCount; i++)
{
background = stamper.GetUnderContent(i);
background.AddTemplate(page, 0, 0);
}
// Close the Destination stamper
stamper.Close();
}
And example call is:
CreatePdfwithBackGround(#"C:\TEST\MainPDF.pdf", #"C:\TEST\BackGroundTemplate.pdf", #"C:\TEST\FinalPDFOutput.pdf");

Related

iTextSharp : create one more page copying last page

I have a PDF file with headers, footers etc on every page. I need to extend count of pages, if text is very long (I have variable text). For example:
if (countOfRecords > 120)
{
// add one more page like second page of template (which does not have content, only header/footer
}
Is it possible?
I implemented it the following way: created PDF file with "empty" page (means only with necessary headers/footers) and then add it to main PDF if necessary how many times as necessary:
PdfReader pdfReader = new PdfReader(model.Input);
Document document = new Document(pdfReader.GetPageSizeWithRotation(1));
using (MemoryStream ms = new MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page = writer.GetImportedPage(pdfReader, 1);
cb.AddTemplate(page, 0, 0);
int countOfPages = (int)Math.Ceiling(Convert.ToDecimal(model.ActiveDriverList.Count - countDriversOnFirstPage) / countDriversOnEmptyPage);
for (int i = 0; i < countOfPages; i++)
{
PdfReader readerPage = new PdfReader(model.EmptyPage);
readerPage.ConsolidateNamedDestinations();
document.SetPageSize(pdfReader.GetPageSizeWithRotation(1));
document.NewPage();
PdfImportedPage importedPage = writer.GetImportedPage(readerPage, 1);
cb = AddTextDriversNextPage(cb, model.ActiveDriverList, i + 1);
cb.AddTemplate(importedPage, 0, 0);
}
document.Close();
writer.Close();
return ms.ToArray();
}

pdf stamper, pdfEventHandler not working when trying to add page number on the pdf document using itext

I am using itext to generate a pdf document but I am trying to use the existing solutions to add page number to the pdf document that is being generated but none of them seems to be working for me.
I tried using something like
using (MemoryStream stream = new MemoryStream())
{
PdfReader reader = new PdfReader(bytes);
using (PdfStamper stamper = new PdfStamper(reader, stream))
{
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
but my code doesnt recognize PdfStamper and asks me to create a class.
Similarly, I tried using
MemoryStream ms = new MemoryStream();
PdfReader reader = new PdfReader(pdf);
int n = reader.NumberOfPages;
Rectangle psize = reader.GetPageSize(1);
There is error on .NumberOfPages and .GetPageSize.
I also tried creating a separate PageEventHandler class but the problem remains same.
Right now, I am able to generate pdf but I want to add page number and I have a code like
private MemoryStream MakeDocument(Application application)
{
MemoryStream ms = new MemoryStream();
PdfWriter writer = new PdfWriter(ms);
PdfDocument pdfDocument = new PdfDocument(writer);
using (var document = new Document(pdfDocument))
{
var sections = new List<IDocumentSection>
{
new Header(),
new Projects(application.Projects),
//Footer
};
foreach (var section in sections)
section.AddTo(document);
Rectangle pageSize;
PdfCanvas canvas;
int n = pdfDocument.GetNumberOfPages();
for (int i = 1; i <= n; i++)
{
PdfPage page = pdfDocument.GetPage(i);
pageSize = page.GetPageSize();
canvas = new PdfCanvas(page);
canvas.BeginText()
.SetFontAndSize(PdfFontFactory.CreateFont(FontConstants.HELVETICA), 7)
.MoveText(pageSize.GetWidth() / 2 - 7, 10)
.ShowText(i.ToString())
.ShowText(" of ")
.ShowText(n.ToString())
.EndText();
}
}
return ms;
var outputStream = MakeDocument(application);
var response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new ByteArrayContent(outputStream.ToArray())
};
response.Content.Headers.Add("Content-Type", "application/pdf");
return response;
But it is complaining at GetPageSize
Object reference not set to an instance of an object. Even if I set page size as A4, it starts to complain at canvas = new PdfCanvas(page);
It seems that you are using iText 7. Or rather, that's what I assume when I see:
PdfWriter writer = new PdfWriter(ms);
PdfDocument pdfDocument = new PdfDocument(writer);
Document document = new Document(pdfDocument);
The PdfStamper class is an iText 5 class. It doesn't exist in iText 7. See Chapter 5 of the jump-start tutorial. You probably want something like this:
MemoryStream stream = new MemoryStream();
PdfWriter writer = new PdfWriter(stream);
PdfReader reader = new PdfReader(bytes);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
Document document = new Document(pdfDoc);
Rectangle pageSize;
PdfCanvas canvas;
int n = pdfDoc.GetNumberOfPages();
for (int i = 1; i <= n; i++) {
PdfPage page = pdfDoc.GetPage(i);
pageSize = page.GetPageSize();
canvas = new PdfCanvas(page);
// draw page numbers on the canvas
}
pdfDoc.close();
If you aren't using iText 7, then there's something wrong in your question. In that case you should clarify what you mean when you use the concepts PdfStamper and PdfEventHandler in the same sentence, because that doesn't make any sense.

itextsharp adding image to existing pdf

i am trying to add an image using itextsharp but not having any luck
there are a ton of tutorials for adding an image to a new pdf doc but not and existing pdf so the .add menthod is not avaivlable
i am tring to do use the stamper write method to add image
and i dont get any errors but no image shows up
PdfReader reader = new PdfReader(pdfIn); //get pdf
if (File.Exists(pdfOut)) File.Delete(pdfOut); //reset
FileStream fs = new FileStream(pdfOut, FileMode.Create);
PdfStamper stamper = new PdfStamper(reader, fs);
try
{
// Convert base64string to bytes array
Byte[] bytes = Convert.FromBase64String(base64decode);
iTextSharp.text.Image sigimage = iTextSharp.text.Image.GetInstance(bytes);//
sigimage.SetAbsolutePosition(10, 10);
sigimage.ScaleToFit(140f, 120f);
stamper.Writer.Add(sigimage);
}catch (DocumentException dex){//log exception here
}catch (IOException ioex){//log exception here
}
AcroFields fields = stamper.AcroFields;
//repeat for each pdf form fill field
fields.SetField("agencyName", name.Value);
stamper.FormFlattening = true; // set to true to lock pdf from being editable
stamper.Writer.CloseStream = true;
stamper.Close();
reader.Close();
fs.Close();
I think you try the following adding it to bytes
PdfReader reader = new PdfReader(pdfIn)
FileStream fs = new FileStream(pdfOut, FileMode.Create);
var stamper = new PdfStamper(reader, fs);
var pdfContentByte = stamper.GetOverContent(1);
iTextSharp.text.Image sigimage = iTextSharp.text.Image.GetInstance(bytes);
sigimage.SetAbsolutePosition(100, 100);
pdfContentByte.AddImage(sigimage);
using following code you can able to add image to each page in an existing pdf file. ( I use this code for desktop application)
string FileLocation = #"C:\\test\\pdfFileName.pdf"; // file path of pdf file
var uri = new Uri(#"pack://application:,,,/projrct_name;component/View/Icons/funnelGreen.png"); // use image from project/application folder (this image will insert to pdf)
var resourceStream = Application.GetResourceStream(uri).Stream;
PdfReader pdfReader = new PdfReader(FileLocation);
PdfStamper stamp = new PdfStamper(pdfReader, new FileStream(FileLocation.Replace(".pdf", "(tempFile).pdf"), FileMode.Create));iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(resourceStream), System.Drawing.Imaging.ImageFormat.Png);
img.SetAbsolutePosition(125, 350); // set the position in the document where you want the watermark to appear.
img.ScalePercent(35f);// not neccessory, use if you want to adjust image
img.ScaleToFit(140f, 100f); // not neccessory, use if you want to adjust image
PdfContentByte waterMark;
for (int page = 1; page <= pdfReader.NumberOfPages; page++) // for loop will add image to each page. Based on the condition you can add image to single page also
{
waterMark = stamp.GetOverContent(page);
waterMark.AddImage(img);
}
stamp.FormFlattening = true;
stamp.Close();// closing the pdfStamper, the order of closing must be important
pdfReader.Close();
File.Delete(FileLocation);
File.Move(FileLocation.Replace(".pdf", "(tempFile).pdf"), FileLocation);

Adding text to each page of PDF with itext instead of just the first page

I'm trying to add text to each page of a PDF using this code which works great, but this code is only for adding text to the first page:
//variables
String pathin = #"C:\Users\root\Desktop\temp\test.pdf";
String pathout = #"C:\Users\root\Desktop\temp\test2.pdf";
//create a document object
//var doc = new Document(PageSize.A4);
//create PdfReader object to read from the existing document
PdfReader reader = new PdfReader(pathin);
//create PdfStamper object to write to get the pages from reader
PdfStamper stamper=new PdfStamper(reader, new FileStream(pathout, FileMode.Create));
// PdfContentByte from stamper to add content to the pages over the original content
PdfContentByte pbover = stamper.GetOverContent(1);
//add content to the page using ColumnText
ColumnText.ShowTextAligned(pbover, Element.ALIGN_LEFT, new Phrase("Hello World"), 10, 10, 0);
// PdfContentByte from stamper to add content to the pages under the original content
//PdfContentByte pbunder = stamper.GetUnderContent(1);
//close the stamper
stamper.Close();
I've seen examples using:
for (var i = 1; i <= reader.NumberOfPages; i++)
{
document.NewPage();
var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
var importedPage = writer.GetImportedPage(reader, i);
To iterate through each page, but I'm having trouble tying that into my code above. Any helps would be much appreciated, thanks.
in your first snippet, you hardcode the page number:
stamper.GetUnderContent(1);
In your second snippet, you loop over the pages:
for (var i = 1; i <= reader.NumberOfPages; i++) {
}
Now combine these two snippets:
for (var i = 1; i <= reader.NumberOfPages; i++) {
PdfContentByte pbunder = stamper.GetUnderContent(i);
// do stuff with bunder
}

how to append pages from file2.pdf to file1.pdf

how to append all the pages in file1.pdf from file2.pdf using (C#) itextsharp
insert page method.please provide the sample code.
i found this code on itext pdf please provide the sample code to work for c#
ColumnText ct = new ColumnText(null);
while (rs.next()) {
ct.addElement(new Paragraph(24,
new Chunk(rs.getString("country"))));
}
PdfReader reader = new PdfReader(src);
PdfReader stationery = new PdfReader(Stationery.STATIONERY);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
PdfImportedPage page = stamper.getImportedPage(stationery, 1);
int i = 0;
while(true) {
stamper.insertPage(++i, reader.getPageSize(1));
stamper.getUnderContent(i).addTemplate(page, 0, 0);
ct.setCanvas(stamper.getOverContent(i));
ct.setSimpleColumn(36, 36, 559, 770);
if (!ColumnText.hasMoreText(ct.go()))
break;
}
stamper.close();
Have a look at Simple .NET PDF Merger article.
The presented PDF merger uses the open source PDF library iTextSharp
to process PDF files.

Categories