Reputation: 1228
How to write Text on different pages on exiting pdf which have more then 1 page. For example 'Hitesh Second Page' I want to write this word on second page 'Hitesh Third Page' I want to write this word on Third page
Below code work only for pdf which have one page.
string fileName = "test.pdf";
string oldFile = System.Web.Hosting.HostingEnvironment.MapPath("~/AuthDoc/CoverPage.pdf");
string newFile = System.Web.Hosting.HostingEnvironment.MapPath(fileName);
// 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);
string text = "";
cb.BeginText();
text = "Hitesh Third Page";
cb.ShowTextAligned(3, text,500,500, 0);
cb.EndText();
cb.BeginText();
text = "Hitesh Second Page";
cb.ShowTextAligned(2, text,500,500, 0);
cb.EndText();
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate( page, 0, 0);
document.Close();
fs.Close();
writer.Close();
reader.Close();
byte[] bytes = System.IO.File.ReadAllBytes(newFile);
return bytes;
Thanks, Hitesh
Upvotes: 0
Views: 965
Reputation: 95928
When using a Document
/ PdfWriter
pair to create a document, you create the pages in their final order, i.e. you first create the first page, then the second, then the third, ...
In your code you appear to try to start by creating the third page and then continue by creating the second one. You'll have to sort the code accordingly.
As soon as you have sorted your code, you can use the Document
method NewPage
to switch to the next page:
document.NewPage();
Beware, though, iText ignores the NewPage
call if there is no content whatsoever on the page in question. To override this, you can make iText believe it is not empty using the PdfWriter
property PageEmpty
before calling NewPage
:
writer.PageEmpty = false;
document.NewPage();
That been said, though...
How to write Text on different pages on exiting pdf
For such a task you should not use a Document
/ PdfWriter
pair to start with, use a PdfReader
/ PdfStamper
pair! In a PdfStamper
you can quite freely jump between pages...
Upvotes: 1