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.
Related
I have this asp.net mvc C# project that returns a downloadable pdf file with A5 page size, and everything seems fine, but when I open the downloaded file and proceed to the print dialog box, I don't get the A5 sheet size by default, but Letter.
What am I missing? Is there a way to achieve this?
Here's the code, thanks in advance:
MemoryStream ms = new MemoryStream();
PdfWriter pw = new PdfWriter(ms);
PdfDocument pdfDocument = new PdfDocument(pw);
Document doc = new Document(pdfDocument, PageSize.A5.Rotate());
doc.SetMargins(5, 5, 5, 5);
//Here I add the content...
doc.Close();
byte[] bytesStream = ms.ToArray();
ms = new MemoryStream();
ms.Write(bytesStream, 0, bytesStream.Length);
ms.Position = 0;
return File(ms, "application/pdf", ID + ".pdf");
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");
I have two fillable pdf files and did the code to merge those pdfs into one single pdf. Below is my code for that.
public void PDFSplit()
{
List<string> files=new List<string>();
files.Add(Server.MapPath("~/Template/sample_pdf.pdf"));
files.Add(Server.MapPath("~/Template/temp/sample_pdf.pdf"));
//call method
Merge(files, Server.MapPath("~/Template/sample_pdf_123.pdf"));
}
//Merge pdf
public void Merge(List<String> InFiles, String OutFile)
{
using (FileStream stream = new FileStream(OutFile, FileMode.Create))
using (iTextSharp.text.Document doc = new iTextSharp.text.Document())
using (PdfCopy pdf = new PdfCopy(doc, stream))
{
doc.Open();
PdfReader reader = null;
PdfImportedPage page = null;
InFiles.ForEach(file =>
{
reader = new PdfReader(file);
for (int i = 0; i < reader.NumberOfPages; i++)
{
page = pdf.GetImportedPage(reader, i + 1);
pdf.AddPage(page);
}
pdf.FreeReader(reader);
reader.Close();
});
}
}
The code is working fine, but the problem is when I am trying to read that new generated merged file, it's not showing fields using AcroFields.
//To read pdf data
PdfReader reader = null;
reader = new PdfReader(Server.MapPath("~/Template/sample_pdf_123.pdf"));
AcroFields pdfFormFields = reader.AcroFields;
You are unable to marge fallible PDF files because you are using an old version of iText. Please upgrade to iText 7 for .NET and read the iText 7 jump-start tutorial, more specifically chapter 6 where it says:
Merging forms
This is how it's done:
PdfDocument destPdfDocument = new PdfDocument(new PdfWriter(dest));
PdfDocument[] sources = new PdfDocument[] {
new PdfDocument(new PdfReader(SRC1)),
new PdfDocument(new PdfReader(SRC2)) };
PdfPageFormCopier formCopier = new PdfPageFormCopier();
foreach (PdfDocument sourcePdfDocument in sources) {
sourcePdfDocument.CopyPagesTo(1,
sourcePdfDocument.GetNumberOfPages(), destPdfDocument, formCopier);
sourcePdfDocument.Close();
}
destPdfDocument.Close();
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);
I want to convert an image to PDF and add a watermark to it. I used iTextSharp to convert it. I successfully converted the image file to pdf but I'm not able to add watermark to it without creating another pdf file.
The code below creates a PDF file and also adds custom attributes,
function watermarkpdf is used to add watermark and pdfname is given as the arguement
foreach (string filenm in Images)
using (var imageStream = new FileStream(filenm, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
doc.NewPage();
iTextSharp.text.Image jpeg = iTextSharp.text.Image.GetInstance(filenm);
float width = doc.PageSize.Width;
float height = doc.PageSize.Height;
jpeg.ScaleToFit(width,height);
doc.Add(jpeg);
}
doc.AddHeader("name", "vijay");
watermarkpdf(pdfname);
The watermarkpdf function is given below.
PdfReader pdfReader = new PdfReader(txtpath.Text+"\\pdf\\" + pdfname);
FileStream stream = new FileStream(txtpath.Text + pdfname,FileMode.Open);
PdfStamper pdfStamper = new PdfStamper(pdfReader, stream);
for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++)
{
Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(pageIndex);
PdfContentByte pdfData = pdfStamper.GetUnderContent(pageIndex);
pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 40);
PdfGState graphicsState = new PdfGState();
graphicsState.FillOpacity = 0.4F;
pdfData.SetGState(graphicsState);
pdfData.SetColorFill(BaseColor.BLUE);
pdfData.BeginText();
pdfData.ShowTextAligned(Element.ALIGN_CENTER, "SRO-Kottarakkara", pageRectangle.Width / 2, pageRectangle.Height / 2, 45);
pdfData.EndText();
}
pdfStamper.Close();
stream.Close();
iTextSharp doesn't support "in-place editing" of files, only reading existing files and creating new files. The problem is that it would have to write to something that is being written to which could be very problematic.
However, instead of using a file you can create your image in a MemoryStream, grab the bytes from that and pipe that to the PdfReader, all with minimal changes to your code. All of the PDF writing functions that take files actually work with the abstract Stream class and which MemoryStream inherits from so they can be used interchangeably. Below is some basic code that should show you what I'm talking about. I don't have an IDE currently so there might be a typo or two but for the most part it should work.
//Image part
//We will dump the bytes from the memory stream to the variable below later
byte[] bytes;
using (MemoryStream ms = new MemoryStream()){
Document doc = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.GetInstance(doc, ms);
doc.Open();
//foreach (string filenm in Images)
//...
doc.Close();
//Dump the bytes, make sure to use ToArray() and not GetBuffer()
bytes = ms.ToArray();
}
//Watermark part
//Read from our bytes
PdfReader pdfReader = new PdfReader(bytes);
FileStream stream = new FileStream(txtpath.Text + pdfname,FileMode.Open);
//...