Remove metadata from existing Pdf using iTextsharp - c#

I created a pdf and added a metadata into it and also encrypted it uisng iTextsharp library.
Now I want to remove the encryption from the pdf. I successfully did so using iTextSharp but was not able to remove the metadata that I added.
Can anyone please giude me how can I remove the metadata. Its urgent.
Thanks.

When removing meta data it is easiest to work directly with the PdfReader object. Once you do that you can write that back to disk. The code below is a full working C# 2010 WinForms application targeting iTextSharp 5.1.2.0. It first creates a PDF with some meta data, then it modifies an in-memory version of the PDF using a PdfReader, and finally writes the changes to disk. See the code for additional comments.
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
//File with meta data added
string InputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
//File with meta data removed
string OutputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf");
//Create a file with meta data, nothing special here
using (FileStream FS = new FileStream(InputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (Document Doc = new Document(PageSize.LETTER)) {
using (PdfWriter writer = PdfWriter.GetInstance(Doc, FS)) {
Doc.Open();
Doc.Add(new Paragraph("Test"));
//Add a standard header
Doc.AddTitle("This is a test");
//Add a custom header
Doc.AddHeader("Test Header", "This is also a test");
Doc.Close();
}
}
}
//Read our newly created file
PdfReader R = new PdfReader(InputFile);
//Loop through each piece of meta data and remove it
foreach (KeyValuePair<string, string> KV in R.Info) {
R.Info.Remove(KV.Key);
}
//The code above modifies an in-memory representation of the PDF, we need to write these changes to disk now
using (FileStream FS = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (Document Doc = new Document()) {
//Use the PdfCopy object to copy each page
using (PdfCopy writer = new PdfCopy(Doc, FS)) {
Doc.Open();
//Loop through each page
for (int i = 1; i <= R.NumberOfPages; i++) {
//Add it to the new document
writer.AddPage(writer.GetImportedPage(R, i));
}
Doc.Close();
}
}
}
this.Close();
}
}
}

Related

Pdf Merge with itext sharp

I am trying to create a desktop application combining existing pdf files into one.
I found some code that helps me with my design and selecting the files and merging them but my code creates pdf files and then sends the new file to the desktop. I need my code to grab existing pdf files and merging them together to create a file with those files together and have it sent to my desktop. Attached is my code, please let me know what I need to fix. I am very new to C# I understand basics but I am unsure where to change things and how to in this certain area.
namespace mergePdf
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnMerge_Click(object sender, EventArgs e)
{
//Folder that we'll work from
string workingFolder =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string pdf1 = Path.Combine(workingFolder, "pdf1.pdf");//PDF
with solid red background color
string pdf2 = Path.Combine(workingFolder, "pdf2.pdf");//PDF
with text
string pdf3 = Path.Combine(workingFolder, "pdf3.pdf");
//Merged PDF
//Create a basic PDF filled with red, nothing special
using (FileStream fs = new FileStream(pdf1, FileMode.Create,
FileAccess.Write, FileShare.None))
{
using (Document doc = new Document(PageSize.LETTER))
{
using (PdfWriter writer = PdfWriter.GetInstance(doc,
fs))
{
doc.Open();
PdfContentByte cb = writer.DirectContent;
cb.SetColorFill(BaseColor.RED);
cb.Rectangle(0, 0, doc.PageSize.Width,
doc.PageSize.Height);
cb.Fill();
doc.Close();
}
}
}
//Create a basic PDF with a single line of text, nothing
special
using (FileStream fs = new FileStream(pdf2, FileMode.Create,
FileAccess.Write, FileShare.None))
{
using (Document doc = new Document(PageSize.LETTER))
{
using (PdfWriter writer = PdfWriter.GetInstance(doc,
fs))
{
doc.Open();
doc.Add(new Paragraph("This is a test"));
doc.Close();
}
}
}
//Create a basic PDF
using (FileStream fs = new FileStream(pdf3, FileMode.Create,
FileAccess.Write, FileShare.None))
{
using (Document doc = new Document(PageSize.LETTER))
{
using (PdfWriter writer = PdfWriter.GetInstance(doc,
fs))
{
doc.Open();
//Get page 1 of the first file
PdfImportedPage imp1 = writer.GetImportedPage(new
PdfReader(pdf1), 1);
//Get page 2 of the second file
PdfImportedPage imp2 = writer.GetImportedPage(new
PdfReader(pdf2), 1);
//Add the first file to coordinates 0,0
writer.DirectContent.AddTemplate(imp1, 0, 0);
//Since we don't call NewPage the next call will
operate on the same page
writer.DirectContent.AddTemplate(imp2, 0, 0);
doc.Close();
}
}
}
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
textBoxPdfFile1Path.Text =
System.IO.Path.Combine(Application.StartupPath,
#"C:\Users\jesse\Downloads");
textBoxPdfFile2Path.Text =
System.IO.Path.Combine(Application.StartupPath,
#"C:\Users\jesse\Downloads");
}
private void btnSelectFile1_Click(object sender, EventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
fd.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
if (fd.ShowDialog() == DialogResult.OK)
{
textBoxPdfFile1Path.Text = fd.FileName;
}
}
private void btnSelectFile2_Click(object sender, EventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
fd.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
if (fd.ShowDialog() == DialogResult.OK)
{
textBoxPdfFile2Path.Text = fd.FileName;
}
}
}
}
I expect the output to combine existing files into one file which will be sent to my desktop. Right now it creates two pdf sample files and combines them but I have no idea how to select from existing instead.
Using the below code should do what you want as far merging the documents.
To get a list of the actual paths to the individual pdfs is up to you on how to do.
Once the FileStream is closed your document should be created at the specified 'newPdfPath' path.
using (FileStream stream = new FileStream(newPdfPath, FileMode.Create))
{
Document document = new Document();
PdfCopy pdf = new PdfCopy(document, stream);
PdfReader reader = null;
document.Open();
foreach (var item in listOfPathsToPDFs)
{
reader = new PdfReader(item);
pdf.AddDocument(reader);
reader.Close();
}
document.Close();
}

ITextSharp Save PDF without Fields

I want to save a PDF file in a flatted mode. I have tried all the online solution but never works in my code.
I have a file generated with ITextSharp and Acrofields. When i try to set the option pdf.FormFlattening = true; it doesn't work for my solution.
The file is generated from an "Adobe Static PDF form" created with Adobe Livecycle Designer
This is my function:
using (var streamPdf = new MemoryStream())
{
PdfStamper pdf;
using (var pdfReader = new PdfReader(Application.StartupPath + PathToFile + Template))
using (pdf = new PdfStamper(pdfReader, streamPdf))
{
AcroFields pdfFormFields = pdf.AcroFields;
foreach (var field in fields)
{
pdfFormFields.SetField(field.FieldName, field.FieldValue.Trim());
}
}
foreach (var de in pdfReader.AcroFields.Fields)
{
pdfFormFields.SetFieldProperty(de.Key.ToString(),"setfflags",PdfFormField.FF_READ_ONLY,null);
}
pdf.FormFlattening = true;
pdf.AcroFields.GenerateAppearances = true;
pdf.Close();
_pdf = streamPdf.ToArray();
}
string filename = "name.pdf";
using (var fs = new FileStream(filename, FileMode.Create))
{
fs.Write(_pdf, 0, _pdf.Count());
fs.Close();
}
The file generated is a static PDF and i need to have a PDF without Fields.
Thanks to all

IDE error on the itextSharp code: "A field initializer cannot reference the non static field"

I am using the following code for watermarking my PDF
using System;
using System.Collections.Generic;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
namespace WatermarkDemo
{
public class Class1
{
string watermarkedFile = "Watermarked.pdf";
// Creating watermark on a separate layer
// Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document
PdfReader reader1 = new PdfReader(originalFile);
using (FileStream fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None))
// Creating iTextSharp.text.pdf.PdfStamper object to write Data from iTextSharp.text.pdf.PdfReader object to FileStream object
using (PdfStamper stamper = new PdfStamper(reader1, fs))
{
// Getting total number of pages of the Existing Document
int pageCount = reader1.NumberOfPages;
// Create New Layer for Watermark
PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer);
// Loop through each Page
for (int i = 1; i <= pageCount; i++)
{
// Getting the Page Size
Rectangle rect = reader1.GetPageSize(i);
// Get the ContentByte object
PdfContentByte cb = stamper.GetUnderContent(i);
// Tell the cb that the next commands should be "bound" to this new layer
cb.BeginLayer(layer);
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50);
PdfGState gState = new PdfGState();
gState.FillOpacity = 0.25f;
cb.SetGState(gState);
cb.SetColorFill(BaseColor.BLACK);
cb.BeginText();
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, rect.Width / 2, rect.Height / 2, 45f);
cb.EndText();
// Close the layer
cb.EndLayer();
}
}
}
}
I don't know why I am getting red squiggly line under most of my variables. Most of them say:
A field initializer cannot reference the non static field.
What can I do to fix this?
You have put your code immediately into the class body:
namespace WatermarkDemo
{
public class Class1
{
string watermarkedFile = "Watermarked.pdf";
// Creating watermark on a separate layer
// Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document
PdfReader reader1 = new PdfReader(originalFile);
using (FileStream fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None))
...
You should put it into a method
namespace WatermarkDemo
{
public class Class1
{
void myMethod()
{
string watermarkedFile = "Watermarked.pdf";
// Creating watermark on a separate layer
// Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document
PdfReader reader1 = new PdfReader(originalFile);
using (FileStream fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None))
...

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();
}
}

Pdf Merge/Overlap with iText

I have used iText for some various utility, such us merge and editing of pdf files with success. Now I need to overlap 2 pdf pages:
For Instance:
INPUT:
PDF#1 (1 Page)
PDF#2 (1 Page)
OUTPUT:
PDF#3 (1 Page: This is the result of the 2 Input Pages Overlapped)
I don't know if it's possible to do this with iText latest version. I am also considering to use one of the 2 input PDF Files as background for the PDF Output Files.
Thank you in advance.
It's actually pretty easy to do. The PdfWriter object has an instance method called GetImportedPage() which returns a PdfImportedPage object. This object can be passed to a PdfContentByte's AddTemplate() method.
GetImportedPage() takes a PdfReader object and the page number that you want to get. You can get a PdfContentByte from an instance of a PdfWriter's DirectContent property.
The code below is a full working C# 2010 WinForms app targeting iTextSharp 5.1.2.0 that shows this all off. It first creates two files on the desktop, the first with just a solid red background color and the second with just a paragraph. It then combines those two files overlapping into a third document. See the code for additional comments.
using System;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
//Folder that we'll work from
string workingFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string pdf1 = Path.Combine(workingFolder, "pdf1.pdf");//PDF with solid red background color
string pdf2 = Path.Combine(workingFolder, "pdf2.pdf");//PDF with text
string pdf3 = Path.Combine(workingFolder, "pdf3.pdf");//Merged PDF
//Create a basic PDF filled with red, nothing special
using (FileStream fs = new FileStream(pdf1, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (Document doc = new Document(PageSize.LETTER)) {
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
PdfContentByte cb = writer.DirectContent;
cb.SetColorFill(BaseColor.RED);
cb.Rectangle(0, 0, doc.PageSize.Width, doc.PageSize.Height);
cb.Fill();
doc.Close();
}
}
}
//Create a basic PDF with a single line of text, nothing special
using (FileStream fs = new FileStream(pdf2, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (Document doc = new Document(PageSize.LETTER)) {
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
doc.Add(new Paragraph("This is a test"));
doc.Close();
}
}
}
//Create a basic PDF
using (FileStream fs = new FileStream(pdf3, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (Document doc = new Document(PageSize.LETTER)) {
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
//Get page 1 of the first file
PdfImportedPage imp1 = writer.GetImportedPage(new PdfReader(pdf1), 1);
//Get page 2 of the second file
PdfImportedPage imp2 = writer.GetImportedPage(new PdfReader(pdf2), 1);
//Add the first file to coordinates 0,0
writer.DirectContent.AddTemplate(imp1, 0, 0);
//Since we don't call NewPage the next call will operate on the same page
writer.DirectContent.AddTemplate(imp2, 0, 0);
doc.Close();
}
}
}
this.Close();
}
}
}

Categories

Resources