How to set zoom level to pdf using iTextSharp? - c#

I need to set the zoom level 75% to pdf file using iTextSharp. I am using following code to set the zoom level.
PdfReader reader = new PdfReader("input.pdf".ToString());
iTextSharp.text.Document doc = new iTextSharp.text.Document(reader.GetPageSize(1));
doc.OpenDocument();
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("Zoom.pdf", FileMode.Create));
PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 0.75f);
doc.Open();
PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);
writer.SetOpenAction(action);
doc.Close();
But I am getting the error "the page 1 was request but the document has only 0 pages" in the doc.Close();

You need to use PdfStamper (as indicated by mkl) instead of PdfWriter (as made clear by Chris Haas). Please take a look at the AddOpenAction example:
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, reader.getPageSize(1).getHeight(), 0.75f);
PdfAction action = PdfAction.gotoLocalPage(1, pdfDest, stamper.getWriter());
stamper.getWriter().setOpenAction(action);
stamper.close();
reader.close();
}
The result is a PDF that opens with a zoom factor of 75%.

Related

Create PDF with iTextSharp without saving the file

I am using Visual Studio 2013, c# Windows Application, iTextSharp:
I can easily create/save a pdf file and write to it but is there a way to just use a pdf file and write to it without first saving it? I don't want to be creating a temporary pdf file every-time someone runs a report. Thanks in Advance !!
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10,10,42,35);
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("Test.pdf",
FileMode.Create));
doc.Open();
\\\\ Then I do a bunch of stuff, then do a close
doc.Close();
You can use a MemoryMappedFile and write to it and it is not disk based.
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("INMEMORYPDF.pdf", 1000000))
{
PDFPageMargins margins = new PDFPageMargins(10, 10, 10, 10);
var document = new Document((_pageWidth > 540) ? PageSize.A4.Rotate() : PageSize.A4, margins.Left, margins.Right, margins.Top, margins.Bottom);
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
PdfWriter.GetInstance(document, stream);
document.Open();
//MODIFY DOCUMENT
document.Close();
}
byte[] content;
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
BinaryReader rdr = new BinaryReader(stream);
content = new byte[mmf.CreateViewStream().Length];
rdr.Read(content, 0, (int)mmf.CreateViewStream().Length);
}
return content;
}

Font style is not preserved when converting HTML to PDF using ItextSharp

I'm trying to convert HTML to PDF, but the font style isn't being properly applied to the PDF. Below is my code (using itextsharp.dll):
Document document = new Document();
FileStream fs = new FileStream(fileName, FileMode.Create);
PdfWriter.GetInstance(document, fs);
document.Open();
HTMLWorker htmlWorker = new HTMLWorker(document);
string content = radEditorCollector.Content;
if (string.IsNullOrWhiteSpace(content))
{
content = AppConstants.LetterNotConfigured;
}
htmlWorker.Parse(new StringReader(content));
document.Close();
fs.Close();
//Create document list of each debtor
PdfReader pdfReader = new PdfReader(fileName);
readerList.Add(pdfReader);
You can edit your font with pdfStamper. Here is little idea. You can manage with what you need.
PdfReader pdfReader = new PdfReader(fileName);
PdfStamper pdfStamper = new PdfStamper(pdfReader, fs);
PdfContentByte pdfContentByte = pdfStamper.GetOverContent(1);
BaseFont baseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
pdfContentByte.SetColorFill(BaseColor.BLUE);
pdfContentByte.SetFontAndSize(baseFont, 8);
pdfContentByte.BeginText();
pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Here is your settings", 400, 600, 0);
pdfContentByte.EndText();
pdfStamper.Close();
readerList.Add(pdfReader);
Update:
Change only tag settings. Use before close.
pdfStamper.AcroFields.SetFieldProperty("YOUR_TAG", "textfont",
baseFont, null);

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

Simple PDF created with iTextSharp cannot be opened by Acrobat Reader?

I create simple test PDF document using iTextSharp. I'm just using PdfContentByte to show some text. This is the code:
Document document = new Document();
Stream outStream = new FileStream("D:\\aaa\\test.pdf", FileMode.OpenOrCreate);
PdfWriter writer = PdfWriter.GetInstance(document, outStream);
document.Open();
PdfContentByte to = writer.DirectContent;
to.BeginText();
to.SetFontAndSize(BaseFont.CreateFont(), 12);
to.SetTextMatrix(0, 0);
to.ShowText("aaa");
to.EndText();
document.Close();
outStream.Close();
The file is created but when I try to open it(using Acrobat Reader), all I get is following message:
There was an error opening this
document. There was a problem reading
this document (14).
Where is the problem ? How do I fix it? Thank you
Problem was solved after restarting VS. No code change was made.
I can't seem to replicate the problem you're encountering, but please take into account potential leaks of resources due to any exceptional conditions you may encounter and properly Dispose() those objects as such:
using (Stream outStream = new FileStream("D:\\aaa\\test.pdf", FileMode.OpenOrCreate))
{
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, outStream);
document.Open();
try
{
PdfContentByte to = writer.DirectContent;
to.BeginText();
try
{
to.SetFontAndSize(BaseFont.CreateFont(), 12);
to.SetTextMatrix(0, 0);
to.ShowText("aaa");
}
finally
{
to.EndText();
}
}
finally
{
document.Close();
}
}

How can I crop the PDF page

Can any one help me that how can I cut the PDF page like as Acrobat professional?
This snippet might help you:
public static void CropDocument(string file, string oldchar, string repChar)
{
int pageNumber = 1;
PdfReader reader = new PdfReader(file);
iTextSharp.text.Rectangle size = new iTextSharp.text.Rectangle(
Globals.fX,
Globals.fY,
Globals.fWidth,
Globals.fHeight);
Document document = new Document(size);
PdfWriter writer = PdfWriter.GetInstance(document,
new FileStream(file.Replace(oldchar, repChar),
FileMode.Create, FileAccess.Write));
document.Open();
PdfContentByte cb = writer.DirectContent;
document.NewPage();
PdfImportedPage page = writer.GetImportedPage(reader,
pageNumber);
cb.AddTemplate(page, 0, 0);
document.Close();
}

Categories

Resources