ItextSharp Columntext in my PDF - c#

i´m working at a little program.
I have a PDF with 17 pages and i want to place columntext on some of them.
But after creating the PDF i get only Page one out.
{
string newfile = "newfile.pdf";
FileStream fs = new FileStream(newfile, FileMode.Create, FileAccess.Write);
PdfReader reader = null;
PdfWriter writer = null;
PdfImportedPage page = null;
Document dc = null;
dc = new Document(reader.GetPageSizeWithRotation(1));
writer = PdfWriter.GetInstance(dc, fs);
dc.Open();
int numberOfPages = reader.NumberOfPages;
PdfContentByte cb = writer.DirectContent;
reader = new PdfReader(pdfPath);
for (int i = 1; i <= numberOfPages; i++)
{
page = writer.GetImportedPage(reader, startPage);
cb.AddTemplate(page, 0, 0);
if (startPage == 1)
{
cb.BeginText();
ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase(new Chunk("<<NAME>>", FontFactory.GetFont("c:\\windows\\fonts\\Roboto-BoldCondensed.ttf", 15, BaseColor.BLACK)).SetSkew(0, 10)), 367.7F, 140.7F, 10);
cb.EndText();
}
startPage++;
}
dc.Close();
fs.Close();
writer.Close();
reader.Close();
}
Addition originally posted as answer
I tried to use stamper but the PDF file ist damaged. Something is wrong with my code string newfile = "newfile2.pdf";
FileStream fs = new FileStream(newfile, FileMode.Create, FileAccess.Write);
PdfReader reader = null;
reader = new PdfReader(pdfPath);
PdfStamper stamper = new PdfStamper(reader,fs);
int numberOfPages = reader.NumberOfPages;
PdfContentByte cb;
for (int i = 1; i <= numberOfPages; i++)
{
cb = stamper.GetOverContent(i);
ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase(new Chunk("<<NAME>>", FontFactory.GetFont("c:\\windows\\fonts\\Roboto-BoldCondensed.ttf", 15, BaseColor.BLACK)).SetSkew(0, 10)), 367.7F, 140.7F, 10);
}
fs.Close();
reader.Close();

Related

Unable to Set PDF text colour with Itextsharp and c#

I am trying to set text colour of PDF using Itextsharp and c#.
Below is the snippet.
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(sourcefilePath);
iTextSharp.text.pdf.PdfReader sReader = new iTextSharp.text.pdf.PdfReader(overlayfilePath);
PdfStamper stamper = new PdfStamper(reader, new FileStream(outputFile, FileMode.Create));
int inputDocumentPages = reader.NumberOfPages;
int overlayDocumentPages = sReader.NumberOfPages;
PdfContentByte background;
for (int i = 1; i <= inputDocumentPages; i++)
{
if (i <= overlayDocumentPages)
{
PdfImportedPage page = stamper.GetImportedPage(sReader, i);
background = stamper.GetUnderContent(i);
background.SetColorFill(BaseColor.RED);
background.Fill();
background.AddTemplate(page, 0, 0);
PdfGState state = new PdfGState();
state.FillOpacity = 0.6f;
state.BlendMode = PdfGState.BM_MULTIPLY;
background.SetGState(state);
background.SaveState();
}
}
stamper.Close();
iTextSharp.text.Font fontNormalBlack = iTextSharp.text.FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Blue));
iTextSharp.text.Font fontNormalBlue = iTextSharp.text.FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black));
Document doc = new Document(PageSize.A4);
string caminho = appPath + "//data//temp//" + Guid.NewGuid().ToString() + ".pdf";
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(caminho, FileMode.Create));
doc.SetMargins(70, 70, 70, 70);
doc.AddCreationDate();
doc.Open();
Paragraph paragrafo = new Paragraph();
paragrafo.Alignment = Element.ALIGN_LEFT;
paragrafo.Add(new Chunk("Name: ", fontNormalBlack));
paragrafo.Add(new Chunk("Paulo Muniz" + "\n\n", fontNormalBlue));
paragrafo.Add(new Chunk("Birthday: ", fontNormalBlack));
paragrafo.Add(new Chunk("24/07" + "\n", fontNormalBlue));
doc.Add(paragrafo);
doc.Close();

Converting multiple TIFF Images to PDF using iTextSharp

I’m using WebSite in ASP.NET and iTextSharp PDF library. I have a tiff document image that contains 3 pages, I would want to convert all those 3 tiff pages into 1 PDF file with 3 pages.
I try this but it doesn't work as well...
Please tell me what should I do?
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
Document document = new Document();
using (var stream = new FileStream(#"C:\File\0.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfWriter.GetInstance(document, stream);
document.Open();
using (var imageStream = new FileStream(#"C:\File\0.tiff", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var image = iTextSharp.text.Image.GetInstance(imageStream);
document.Add(image);
}
document.Close();
}
// creation of the document with a certain size and certain margins
iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
// creation of the different writers
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(Server.MapPath("~/App_Data/result.pdf"), System.IO.FileMode.Create));
// load the tiff image and count the total pages
System.Drawing.Bitmap bm = new System.Drawing.Bitmap(Server.MapPath("~/App_Data/source.tif"));
int total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
document.Open();
iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
for (int k = 0; k < total; ++k)
{
bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);
// scale the image to fit in the page
img.ScalePercent(72f / img.DpiX * 100);
img.SetAbsolutePosition(0, 0);
cb.AddImage(img);
document.NewPage();
}
document.Close();
I just copied the code from this answer, and modified it to your example. So credits go to the person who answered the question in the link.
using (var stream = new FileStream(#"C:\File\0.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
var writer = PdfWriter.GetInstance(document, stream);
var bitmap = new System.Drawing.Bitmap(#"C:\File\0.tiff");
var pages = bitmap.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
document.Open();
iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
for (int i = 0; i < pages; ++i)
{
bitmap.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, i);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Bmp);
// scale the image to fit in the page
//img.ScalePercent(72f / img.DpiX * 100);
//img.SetAbsolutePosition(0, 0);
cb.AddImage(img);
document.NewPage();
}
}
document.Close();
}
What I achieved after a long period and based on some searches.
I make a request and the response is PDF or TIFF. The first part is just what I get and how I call the private methods, and that is what you need.
var httpResponse = (HttpWebResponse)(await httpWebRequest.GetResponseAsync());
Stream stream = httpResponse.GetResponseStream();
string contentType = httpResponse.ContentType;
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
FileStream file2;
try
{
switch (contentType)
{
case "application/pdf":
{
string outputfile2 = Path.Combine(zipDirectory, "ixosid_" + icxos + ".pdf");
file2 = new FileStream(outputfile2, FileMode.Create, FileAccess.Write);
ms.WriteTo(file2);
file2.Close();
break;
}
default:
{
string outputfile1 = Path.Combine(zipDirectory, "ixosid_" + icxos + ".tiff");
file2 = new FileStream(outputfile1, FileMode.Create, FileAccess.Write);
ms.WriteTo(file2);
file2.Close();
string[] outfilesTiffPages = ConvertTiffToJpeg(outputfile1);
File.Delete(outputfile1);
string outputfile2 = Path.Combine(zipDirectory, "ixosid_" + icxos + ".pdf");
iTextSharp.text.Document doc= AddPicturesToPDF(outfilesTiffPages, outputfile2);
break;
}
}
}
and I have two private methods
private string[] ConvertTiffToJpeg(string fileName)
{
using (System.Drawing.Image imageFile = System.Drawing.Image.FromFile(fileName))
{
FrameDimension frameDimensions = new FrameDimension(
imageFile.FrameDimensionsList[0]);
// Gets the number of pages from the tiff image (if multipage)
int frameNum = imageFile.GetFrameCount(frameDimensions);
string[] jpegPaths = new string[frameNum];
for (int frame = 0; frame < frameNum; frame++)
{
// Selects one frame at a time and save as jpeg.
imageFile.SelectActiveFrame(frameDimensions, frame);
using (Bitmap bmp = new Bitmap(imageFile))
{
jpegPaths[frame] = String.Format(#"{0}\{1}{2}.jpg",
Path.GetDirectoryName(fileName),
Path.GetFileNameWithoutExtension(fileName),
frame);
bmp.Save(jpegPaths[frame], ImageFormat.Jpeg);
}
}
return jpegPaths;
}
}
private iTextSharp.text.Document AddPicturesToPDF(string[] filesPaths, string outputPdf)
{
FileStream fs = new FileStream(outputPdf, FileMode.Create);
Document pdfdoc = new Document();
PdfWriter.GetInstance(pdfdoc, fs);
pdfdoc.Open();
int size = filesPaths.Length;
int count = 0;
foreach(string imagePath in filesPaths)
{
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath);
img.Alignment = Element.ALIGN_CENTER;
img.SetAbsolutePosition(0, 0);
img.ScaleToFit((PageSize.A4.Width - pdfdoc.RightMargin - pdfdoc.LeftMargin), (PageSize.A4.Height- pdfdoc.BottomMargin - pdfdoc.TopMargin));
pdfdoc.Add(img);
pdfdoc.NewPage();
}
pdfdoc.Close();
return pdfdoc;
}
Maybe I can work with MemoryStream but for now, is working and is what I need.
I searched a lot, and some links that deserve to be mentioned
https://coderedirect.com/questions/178295/convert-tiff-to-jpg-format

iText Sharp in merge Excel file

I merged two PDF files into one PDF file using iText Sharp . But is it possible to merge excel file into PDF file using iText Sharp also? i tried many times but it doesn't work for me.Here is my PDF Merge code:
protected void btnMerge_Click(object sender, EventArgs e)
{
if (file1.HasFile && file2.HasFile)
{
PdfReader pdfReader1 = new PdfReader(file1.PostedFile.InputStream);
PdfReader pdfReader2 = new PdfReader(file2.PostedFile.InputStream);
List<PdfReader> readerList = new List<PdfReader>();
readerList.Add(pdfReader1);
readerList.Add(pdfReader2);
//Define a new output document and its size, type
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
//Get instance response output stream to write output file.
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
foreach (PdfReader reader in readerList)
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
document.Add(iTextSharp.text.Image.GetInstance(page));
}
}
document.Close();
Response.AppendHeader("content-disposition", "inline; filename=OutPut.pdf");
Response.ContentType = "application/pdf";
}
}
private void MergePDFs(string outPutFilePath, params string[] filesPath)
{
List<PdfReader> readerList = new List<PdfReader>();
foreach (string filePath in filesPath)
{
PdfReader pdfReader = new PdfReader(filePath);
readerList.Add(pdfReader);
}
//Define a new output document and its size, type
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
//Create blank output pdf file and get the stream to write on it.
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outPutFilePath, FileMode.Create));
document.Open();
foreach (PdfReader reader in readerList)
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
document.Add(iTextSharp.text.Image.GetInstance(page));
}
}
document.Close();
}
}
}

how to change position of added image in pdf using iTextSharp

I want to change the Image position to be in the top right of the pdf as a logo , this code make my image in the top left and some text wrote on it :
string oldFile = #"D:\Source pdf\Source.pdf";
string newFile = #"D:\Result pdf\Result.pdf";
string imagepath = #"D:\Source pdf\Myiamge.jpg";
Console.WriteLine("iText Demo");
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
iTextSharp.text.Image instanceImg = iTextSharp.text.Image.GetInstance(imagepath);
document.Add(instanceImg);
PdfContentByte cb = writer.DirectContent;
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
document.Close();
fs.Close();
writer.Close();
reader.Close();

ITextSharp insert text to an existing pdf

The title sums it all.
I want to add a text to an existing PDF file using iTextSharp, however i can't find how to do it anywhere in the web...
PS: I cannot use PDF forms.
I found a way to do it (dont know if it is the best but it works)
string oldFile = "oldFile.pdf";
string newFile = "newFile.pdf";
// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
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, 8);
// write the text in the pdf content
cb.BeginText();
string text = "Some random blablablabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 520, 640, 0);
cb.EndText();
cb.BeginText();
text = "Other random blabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(2, text, 100, 200, 0);
cb.EndText();
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();
I hope this can be usefull for someone =) (and post here any errors)
In addition to the excellent answers above, the following shows how to add text to each page of a multi-page document:
using (var reader = new PdfReader(#"C:\Input.pdf"))
{
using (var fileStream = new FileStream(#"C:\Output.pdf", FileMode.Create, FileAccess.Write))
{
var document = new Document(reader.GetPageSizeWithRotation(1));
var writer = PdfWriter.GetInstance(document, fileStream);
document.Open();
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);
var contentByte = writer.DirectContent;
contentByte.BeginText();
contentByte.SetFontAndSize(baseFont, 12);
var multiLineString = "Hello,\r\nWorld!".Split('\n');
foreach (var line in multiLineString)
{
contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, line, 200, 200, 0);
}
contentByte.EndText();
contentByte.AddTemplate(importedPage, 0, 0);
}
document.Close();
writer.Close();
}
}
This worked for me and includes using OutputStream:
PdfReader reader = new PdfReader(new RandomAccessFileOrArray(Request.MapPath("Template.pdf")), null);
Rectangle size = reader.GetPageSizeWithRotation(1);
using (Stream outStream = Response.OutputStream)
{
Document document = new Document(size);
PdfWriter writer = PdfWriter.GetInstance(document, outStream);
document.Open();
try
{
PdfContentByte cb = writer.DirectContent;
cb.BeginText();
try
{
cb.SetFontAndSize(BaseFont.CreateFont(), 12);
cb.SetTextMatrix(110, 110);
cb.ShowText("aaa");
}
finally
{
cb.EndText();
}
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
}
finally
{
document.Close();
writer.Close();
reader.Close();
}
}
Here is a method that uses stamper and absolute coordinates showed in the different PDF clients (Adobe, FoxIt and etc. )
public static void AddTextToPdf(string inputPdfPath, string outputPdfPath, string textToAdd, System.Drawing.Point point)
{
//variables
string pathin = inputPdfPath;
string pathout = outputPdfPath;
//create PdfReader object to read from the existing document
using (PdfReader reader = new PdfReader(pathin))
//create PdfStamper object to write to get the pages from reader
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(pathout, FileMode.Create)))
{
//select two pages from the original document
reader.SelectPages("1-2");
//gettins the page size in order to substract from the iTextSharp coordinates
var pageSize = reader.GetPageSize(1);
// 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
Font font = new Font();
font.Size = 45;
//setting up the X and Y coordinates of the document
int x = point.X;
int y = point.Y;
y = (int) (pageSize.Height - y);
ColumnText.ShowTextAligned(pbover, Element.ALIGN_CENTER, new Phrase(textToAdd, font), x, y, 0);
}
}
Here is a method To print over images:
taken from here.
Use a different layer for your text you're putting over the images, and also make sure to use the GetOverContent() method.
string oldFile = "FileWithImages.pdf";
string watermarkedFile = "Layers.pdf";
// Creating watermark on a separate layer
// Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document
PdfReader reader1 = new PdfReader(oldFile);
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("Layer", 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.GetOverContent(i);
// Tell the cb that the next commands should be "bound" to this new layer
cb.BeginLayer(layer);
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.RED);
cb.SetFontAndSize(bf, 100);
cb.BeginText();
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Some random blablablabla...", rect.Width / 2, rect.Height / 2, - 90);
cb.EndText();
// Close the layer
cb.EndLayer();
}
}

Categories

Resources