Hi i am using below code. When i upload some of PDF's which contain some content and after uploading, their is no content on uploaded PDF. Uploaded PDf is blank. I am using below method of ItextSharp for change the version of Orginial PDF to Defined Version.
private int WriteCompatiblePdf(string fileName, FileUpload filePath)
{
string sNewPdf = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["InterfaxPath"]) + fileName;
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(filePath.FileBytes);
// we retrieve the total number of pages
int n = reader.NumberOfPages;
// step 1: creation of a document-object
iTextSharp.text.Document document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1));
// step 2: we create a writer that listens to the document
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(sNewPdf, FileMode.Create, FileAccess.ReadWrite));
//write pdf that pdfsharp can understand
writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4);
// step 3: we open the document
document.Open();
iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
iTextSharp.text.pdf.PdfImportedPage page;
int rotation;
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(reader.GetPageSizeWithRotation(i));
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
// step 5: we close the document
document.Close();
return n;
}
Any recommendations?
The OP provided a sample "blank" file.
As it turns out, this "blank" file does contain the desired content, it merely is way off-page.
Details
The pages of the document have this media box definition:
/MediaBox[0 7072 612 7864]
Thus, the visible area has x coordinates in 0..612 and y coordinates in 7072..7864. When adding the imported page contents, though, the OP explicitly anchors them explicitly at the coordinates 0,0:
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
The contents of the former page, therefore, are added in the area with y coordinates 0..792. So, they are not visible.
Resolutions
There are different ways to resolve this issue:
add the contents at the position with the correct coordinates, i.e. use
cb.AddTemplate(page, 1f, 0, 0, 1f, x, y);
where x and y are Left and Bottom of reader.GetPageSizeWithRotation(1) (a Rectangle); or
normalize the page size rectangle for the Document constructor to be based in 0,0; or
use a PdfStamper with the PdfReader instead of the PdfWriter and use it to select the desired version.
it's because you're not set any text to be written in the PDF. this is a simple example how to write text
string newFile = #"C:\the path\file.pdf";
Document doc = new Document(iTextSharp.text.PageSize.A4, 10, 10, 42, 35);
PdfWriter write = PdfWriter.GetInstance(doc, new FileStream(newFile,
FileMode.Create));
doc.Open(); // open the connection
Paragraph p1 = new Paragraph("text to be displayed in the first paragraph");
doc.Add(p1); // close the connection
this link will tell you the proper way to write from iTextSharp more advanced
Related
For Bruno
{
This is not a duplicate of "I have normal PDF file, i want to insert blank pages at the end of PDF using itext LIBRARY, without disturbing the PDF contents."
I'm trying to add a blank page after each page in the source PDF - not just 1 blank page at the end of the source PDF document.
}
Using C# (NOT Java) - Does anyone know how to insert a blank page (preferably A4 - Portrait 8.5 x 11) After each page in a PDF using iTextSharp regardless of the page size and orientation of the Source PDF? Each page of the Source PDF can have a different size and orientation.
I've tried the following. It seems to make the blank page following each page the orientation and size of the Source PDF Page but the page from the Source PDF seems to be the orientation and size of the previous blank page:
private string DocumentWithBlankPagesInserted(string fileName, string userComments)
{
string outputFileName = v.tmp + #"\" + v.tmpDir + #"\" + Guid.NewGuid().ToString() + ".pdf";
Document document = new Document();
try
{
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFileName, FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfReader reader = new PdfReader(fileName);
for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++)
{
document.SetPageSize(reader.GetPageSizeWithRotation(pageNumber));
Chunk fileRef = new Chunk();
fileRef.SetLocalDestination(fileName);
PdfImportedPage page1 = writer.GetImportedPage(reader, pageNumber);
Rectangle psize = reader.GetPageSizeWithRotation(pageNumber);
switch (psize.Rotation)
{
case 0:
cb.AddTemplate(page1, 1f, 0, 0, 1f, 0, 0);
break;
case 90:
cb.AddTemplate(page1, 0, -1f, 1f, 0, 0, psize.Height);
break;
case 180:
cb.AddTemplate(page1, -1f, 0, 0, -1f, 0, 0);
break;
case 270:
cb.AddTemplate(page1, 0, 1.0F, -1.0F, 0, psize.Width, 0);
break;
default:
break;
}
document.NewPage();
document.Add(fileRef);
document.NewPage();
}
}
catch (Exception e)
{
throw e;
}
finally
{
document.Close();
}
return outputFileName;
}
As I explained in the comments, this question is a duplicate of How to add blank pages to an existing PDF in java?
You should use PdfStamper instead of PdfWriter (this has been explained a zillion times before in different answers on StackOverflow). Using the InsertPage() method you can add pages of any size you want:
PdfReader reader = new PdfReader(src);
PdfStamper stamper=new PdfStamper(reader, new FileStream(dest, FileMode.Create));
int total = reader.NumberOfPages + 1
for (int pageNumber = total; pageNumber > 0; pageNumber--) {
stamper.InsertPage(pageNumber, PageSize.A4);
}
stamper.Close();
reader.Close();
Note that I add the pages in reverse order. This is elementary logic: adding a page changes the page count and it is harder to keep track of pageNumber if you go from page 1 to total. It's easier do go in the reverse direction.
I'm trying the create a multiple-page pdf using iTextSharp, but I'm having some issue creating a loop to have more than a single page.
My code below is working well for one page; however, my content will not fit into a single page. Thanks.
How can I write a loop to write contents on the first pdf page and the remaining to the second, third, etc...So far, I'm only seeing one page. Thank you.
int height = 600;
int totalPage = 1;
int oldPage = 1;
bool cons = false;
bool st = false;
foreach (string al in combo)
foreach (string al in combo) //my loop to write on the pdf but "combo" has 100 lines, which would fit into a single page.
{
string[] word = al.Split(',');
int strIndex = combo.IndexOf(al);
if (al.Length != 0)
{
if (word[0].ToString().ToUpper().Contains("(REV")==true && cons == false)
{
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 11);
cb.BeginText();
// put the alignment and coordinates here
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "CONSTRUCTION PRINTS", 80, height, 0);
cb.EndText();
height = height - 20;
cons = true;
}
if (word[0].ToString().ToUpper().Contains("(REV")==false && st == false)
{
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 11);
cb.BeginText();
// put the alignment and coordinates here
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "SAG & TENSION CHARTS", 80, height, 0);
cb.EndText();
height = height - 20;
st = true;
}
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 11);
totalPage = totalPage + oldPage;
// write the text in the pdf content
cb.BeginText();
// put the alignment and coordinates here
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, word[0].ToString().ToUpper(), 80, height, 0);
cb.EndText();
// write the text in the pdf content
cb.BeginText();
// put the alignment and coordinates here
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "......................................................................................", 335, height, 0);
cb.EndText();
// write the text in the pdf content
cb.BeginText();
// put the alignment and coordinates here
cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, totalPage.ToString(), 500, height, 0);
cb.EndText();
oldPage = Convert.ToInt32(word[1]);
}
height = height - 20;
}
//// create the new page and add it to the pdf
// reader = new PdfReader(oldFile);//old file
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
//// close the streams and voilá the file should be changed :)
document.Close();
reader.Close();
fs.Close();
writer.Close();
Please go to the official documentation and click Q&A to go to the most frequently asked questions. Pick the Getting started category. The first thing you'll see, is the most popular iText example (which I am porting to C# for your convenience):
// step 1
Document document = new Document();
// step 2
FileStream fs = new FileStream("hello.pdf", FileMode.Create);
PdfWriter.GetInstance(document, fs);
// step 3
document.Open();
// step 4
document.Add(new Paragraph("Hello World!"));
// step 5
document.Close();
In your code, you are adding text at absolute positions by introducing PDF syntax, such as BeginText() (BT) / EndText() (ET) / SetFontAndSize() (Tf). This is creating PDF the hard way. If is very easy to make mistakes, as shown in this question: What is causing syntax errors in a page created with iText?
If you don't know the PDF reference (ISO 32000-1) by heart, you should avoid code like this. Instead you can use objects such as Paragraph, List, PdfPTable... The beauty of adding these objects to a Document using the Add() method, is that a new page gets triggered automagically as soon as a page is full. You can also trigger a new page yourself using:
document.NewPage();
If you want to add text at absolute positions, iText offers convenience methods and objects such as ColumnText. See my answer to Adding footer to existing PDF
You can define a Rectangle and add objects such as Paragraph, List, PdfPTable... Take a look at the answer to the question How to continue an ordered list on a second page? for inspiration:
ColumnText ct = new ColumnText(cb);
ct.AddElement(list);
Rectangle rect = new Rectangle(36, 36, 559, 806);
ct.SetSimpleColumn(rect);
int status = ct.Go();
while (ColumnText.HasMoreText(status)) {
document.NewPage();
ct.SetSimpleColumn(rect);
ct.Go();
}
The while loop is the loop you are looking for.
This question already has an answer here:
Tile PDF pages vertically with iTextSharp
(1 answer)
Closed 8 years ago.
I am trying to divide a PDF into exactly 2 equal halves, saving them as "LeftPDF.pdf" and "RightPDF.pdf".
I tried the code below but it doesn't work:
PdfReader reader = new PdfReader(filepath);
int n = reader.NumberOfPages;
iTextSharp.text.Rectangle psize = reader.GetPageSize(1);
float width = psize.Width/2;
float height = psize.Height;
Document document = new Document(psize);
// target.pdf is A5 Portrait format
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(splitpath, FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
document.NewPage();
PdfImportedPage page1 =writer.GetImportedPage(reader, 1);
cb.AddTemplate(page1, 1, 0, 0, 1, 0, 0);
document.Close();
How can I do this?
As I indicated in my comment, your question has been posted and answered before. This is yet another duplicate of your question: Divide one page PDF file in two pages PDF file
Take a closer look at the TileInTwo example:
public void manipulatePdf(String src, String dest)
throws IOException, DocumentException {
// Creating a reader
PdfReader reader = new PdfReader(src);
int n = reader.getNumberOfPages();
// step 1
Rectangle mediabox = new Rectangle(getHalfPageSize(reader.getPageSizeWithRotation(1)));
Document document = new Document(mediabox);
// step 2
PdfWriter writer
= PdfWriter.getInstance(document, new FileOutputStream(dest));
// step 3
document.open();
// step 4
PdfContentByte content = writer.getDirectContent();
PdfImportedPage page;
int i = 1;
while (true) {
page = writer.getImportedPage(reader, i);
content.addTemplate(page, 0, -mediabox.getHeight());
document.newPage();
content.addTemplate(page, 0, 0);
if (++i > n)
break;
mediabox = new Rectangle(getHalfPageSize(reader.getPageSizeWithRotation(i)));
document.setPageSize(mediabox);
document.newPage();
}
// step 5
document.close();
reader.close();
}
public Rectangle getHalfPageSize(Rectangle pagesize) {
float width = pagesize.getWidth();
float height = pagesize.getHeight();
return new Rectangle(width, height / 2);
}
In this example, we ask the PdfReader instance for the page size of the first page and we create a new rectangle with the same width and only half the height.
We then import each page in the document, and we add it twice on different pages:
once on the odd pages with a negative y value to show the upper half of the original page,
once on the even pages with y = 0 to show the lower half of the original page.
As every page in the original document can have a different size, we may need to change the page size for every new couple of pages.
This example cuts a page in two with an upper part and a lower part. Use simple math and you can adapt the example to cut it in two with a left and a right part. This is done in the example TileInTwo2:
For instance:
public void manipulatePdf(String src, String dest)
throws IOException, DocumentException {
// Creating a reader
PdfReader reader = new PdfReader(src);
int n = reader.getNumberOfPages();
// step 1
Rectangle mediabox = new Rectangle(getHalfPageSize(reader.getPageSizeWithRotation(1)));
Document document = new Document(mediabox);
// step 2
PdfWriter writer
= PdfWriter.getInstance(document, new FileOutputStream(dest));
// step 3
document.open();
// step 4
PdfContentByte content = writer.getDirectContent();
PdfImportedPage page;
int i = 1;
while (true) {
page = writer.getImportedPage(reader, i);
content.addTemplate(page, 0, 0);
document.newPage();
content.addTemplate(page, -mediabox.getWidth(), 0);
if (++i > n)
break;
mediabox = new Rectangle(getHalfPageSize(reader.getPageSizeWithRotation(i)));
document.setPageSize(mediabox);
document.newPage();
}
// step 5
document.close();
reader.close();
}
public Rectangle getHalfPageSize(Rectangle pagesize) {
float width = pagesize.getWidth();
float height = pagesize.getHeight();
return new Rectangle(width / 2, height);
}
You should have no problem to adapt this example so that different PDF documents are created instead of the one containing the left and right part. If that is problematic for you, please post another question.
I have pdf files exported as legal format and want to convert them to letter format (basically shrink them), each file may have 1 to 3 pages, below is the code I tried but I have these problems:
the page size is reduced which is good, but I can't use the margin properties to put the page at the correct borders of the container (the page I kind of shrinked but drawn somewhere at the bottom of the resulted pdf file)
I couldn't increment the number of pages so the code draws both pages, one on top of the other.
Here's the code
PdfImportedPage page;
PdfReader reader = new PdfReader(#"C:\pdf\legalFormat.pdf");
Document doc = new Document(PageSize.A4, 0, 0, 0, 0);
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(#"C:\pdf\letterFormat.PDF", FileMode.Create));
doc.Open();
PdfContentByte cb = writer.DirectContent;
for (int i = 1 ; i < reader.NumberOfPages + 1; i++){
page = writer.GetImportedPage(reader, i); // i is the number of page
float Scale = 0.67f;
cb.AddTemplate(page, Scale, 0, 0, Scale, 0, 0);
}
doc.Close();
Problem solved:
in a main proc run this for test.
string original = args[0];
string inPDF = original;
string outPDF = Directory.GetDirectoryRoot(original) + "temp.pdf";
PdfReader pdfr = new PdfReader(inPDF);
Document doc = new Document(PageSize.LETTER);
Document.Compress = true;
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(outPDF, FileMode.Create));
doc.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
for (int i = 1; i < pdfr.NumberOfPages + 1; i++)
{
page = writer.GetImportedPage(pdfr, i);
cb.AddTemplate(page, PageSize.LETTER.Width / pdfr.GetPageSize(i).Width, 0, 0, PageSize.LETTER.Height / pdfr.GetPageSize(i).Height, 0, 0);
doc.NewPage();
}
doc.Close();
//just renaming, conversion / resize process ends at doc.close() above
File.Delete(original);
File.Copy(outPDF, original);
Hi
I want to add a text in persian language (a right to left language) to the top of an existing pdf file, using iTextSharp Version 5.0.0.0 library.
I use this code:
public static void InsertText(string SourceFileName, string TargetFileName, string Text, int x, int y)
{
PdfReader reader = new PdfReader(SourceFileName);
Document document = new Document(PageSize.A4, 0, 0, 0, 0); // open the writer
FileStream fs = new FileStream(TargetFileName, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
PdfContentByte cb = writer.DirectContent; // select the font properties
FontFactory.RegisterDirectories();
Font fTahoma = FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 10, Font.NORMAL, BaseColor.RED);
writer.SetMargins(0, 0, 0, 0);
ColumnText ct = new ColumnText(writer.DirectContent);
ct.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
Phrase p = new Phrase(Text, fTahoma);
ct.SetText(p);
ct.SetSimpleColumn(x, y, x + 350, y + 20);
ct.Go();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
cb.AddTemplate(page, 0, 0); // close the streams and voilá the file should be changed :)
document.NewPage();
}
document.Close();
fs.Close();
writer.Close();
}
I call InsertText("Source.pdf", "Target.pdf", "Persian message", 10, 800);
My source.pdf page size is: height: 842, width: 595
Unfortunately i get target.pdf with only half of my message! The other vertical half is hidden!
Now the question is: How i can add a right to left language text to the top of an existing pdf file?
Problem: The imported page is probably overwriting the text.
Solution: Add your PdfImportedPage, THEN add the text.