How to turn the page using Itextsharp - c#

Ifound some example.
However, all of the examples use PdfReader.
I want to use PDFWriter.
Below is the code I wrote.
private void CreatePdf(string strPdfPath)
{
FileStream fs = new FileStream(strPdfPath, FileMode.Create, FileAccess.Write, FileShare.None);
Document document = new Document(PageSize.A4, 45, 45, 80, 80);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
document.AddTitle("This is Title");
document.AddCreationDate();
Paragraph content1 = new Paragraph("This is first Page");
document.Add(content1);
document.NewPage();
Paragraph content2 = new Paragraph("This is second Page");
document.Add(content2);
writer.Close();
fs.Close();
}
How to rotate the PDF?

You could do both:
document.open();
// Add some content in portrait
document.setPageSize(PageSize.A4.rotate());
document.newPage();
// Add some content in landscape
document.close();

Related

ItextSharp return a corrupted file after editing existing pdf file

I am new to itextSharp. What I am doing is just editing the old file and instead of saving the new file on the server I just want it to download at the time. but unfortunately after editing the file and being downloaded, file display a message cannot open the file. It may be corrupted.
Here is my code.
public FileStreamResult export( int ? id)
{
string pathin = Server.MapPath(Url.Content("~/PDF/input.pdf"));
PdfReader reader = new PdfReader(pathin);
iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
//FileStream ms = new FileStream(pathout, FileMode.Create, FileAccess.Write);
var ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
writer.CloseStream = false;
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, 18f);
// write the text in the pdf content
cb.BeginText();
string text = "this is text";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 500, 500, 0);
cb.EndText();
cb.BeginText();
text = "this is my post";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 600, 400, 0);
cb.EndText();
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
ms.Position = 0;
document.Close();
//ms.Close();
writer.Close();
reader.Close();
return File(ms, "application/pdf","test.pdf");
}
Any help will be really appreciated. :)
You change the position of the memory stream before closing the document:
ms.Position = 0;
document.Close();
As the trailer of the pdf in the result stream is written during the closing of the document, your change of stream position causes the pdf trailer to be written over the pdf header and the stream position thereafter to not be at the start.
Instead first close the document and the reader (the writer implicitly is closed by closing the document) and reset the stream position thereafter:
document.Close();
reader.Close();
ms.Position = 0;
return File(ms, "application/pdf","test.pdf");

C#, iTextSharp 5.5.10 Shown "Cannot access a closed file." on document close command

I don't know how to solve this because the document seem close before the actual command even I put command to open it again. Please help.
This is my code. When I click the button it will do this and the error will occur at doc.close() line. It shown "Cannot access a closed file." Even I put doc.open() above.
private void run_Click(object sender, EventArgs e)
{
Document doc = new Document(PageSize.A4);
using(FileStream op = new FileStream("text.pdf", FileMode.Create))
{
PdfWriter wri = PdfWriter.GetInstance(doc, op);
Paragraph p = new Paragraph("test");
doc.Open();
doc.Add(p);
}
using (FileStream op = new FileStream("text.pdf", FileMode.Append, FileAccess.Write))
{
PdfWriter wri = PdfWriter.GetInstance(doc, op);
Paragraph p = new Paragraph("test2");
doc.Open();
doc.Add(p);
doc.Close();
}
}
First of all, it is not a correct way to add some contents to an existing PDF by appending a PDF file. If you want to add contents to an existing PDF, please check ITextSharp insert text to an existing pdf.
However, if you just want it to work, you just need to create a new Document instance every time.
private void run_Click(object sender, EventArgs e)
{
Document doc = new Document(PageSize.A4);
using(FileStream op = new FileStream("text.pdf", FileMode.Create))
{
PdfWriter wri = PdfWriter.GetInstance(doc, op);
Paragraph p = new Paragraph("test");
doc.Open();
doc.Add(p);
}
using (FileStream op = new FileStream("text.pdf", FileMode.Append, FileAccess.Write))
{
doc = new Document(PageSize.A4); // this is the fix
PdfWriter wri = PdfWriter.GetInstance(doc, op);
Paragraph p = new Paragraph("test2");
doc.Open();
doc.Add(p);
doc.Close();
}
}

How to rotate text in iTextSharp?

I have searched the web but it looks like that it is not that easy, how can i rotate my text?
Document doc = new Document(new iTextSharp.text.Rectangle(600, 800), 0, 0, 0, 0);
PdfWriter.GetInstance(doc, new FileStream(Directory.GetCurrentDirectory() + "/genpdf.pdf", FileMode.Create));
doc.Open();
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(file);
Chunk c1 = new Chunk("~Comment~"); //rotate 270°
doc.Add(image);
doc.Add(text);
doc.Close();
The answer is in Rotate text answer
The writer is a PdfWriter type, you can get it like:
using (stream = new FileStream(temp_filename, FileMode.Create))
{
iTextSharp.text.Document document = new iTextSharp.text.Document();
PdfWriter writer = PdfWriter.GetInstance(document, stream);

iTextSharp first page text higher

I created a simple pdf with iText.
But why is the position of the text on the first page higher than on all the other pages.
Here is some test code to see where the problem situates:
MemoryStream PDFData = new MeMemoryStream PDFData = new MemoryStream();
Document document = new Document(PageSize.A4, 50, 50, 80, 50);
PdfWriter PDFWriter = PdfWriter.GetInstance(document, PDFData);
document.Open();
Moviecollection movCol = new Moviecollection();
foreach (Movie mov in movCol.Movies)
{
Phrase phr = new Phrase(mov.Description);
document.Add(phr);
document.Add(Chunk.NEWLINE);
}
document.Close();
Any ideas?
thanks,
Filip
I think its to do with Chunk.NEWLINE addition.
I'm guessing you are simulating a paragraph with that Phrase + Newline combination. If you switch to Paragraph object instead, the problem is solved (tested on my machine with your code).
using(MemoryStream PDFData = new MemoryStream())
using(Document document = new Document(PageSize.A4, 50, 50, 80, 50))
{
PdfWriter PDFWriter = PdfWriter.GetInstance(document, PDFData);
document.Open();
Moviecollection movCol = new Moviecollection();
foreach (Movie mov in movCol.Movies)
document.Add(new Paragraph(mov.Description));
}

Create PDF in memory instead of physical file

How do one create PDF in memorystream instead of physical file using itextsharp.
The code below is creating actual pdf file.
Instead how can I create a byte[] and store it in the byte[] so that I can return it through a function
using iTextSharp.text;
using iTextSharp.text.pdf;
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("c:\\Test11.pdf", FileMode.Create));
doc.Open();//Open Document to write
Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
Phrase pharse = new Phrase("This is my second line using Pharse.");
Chunk chunk = new Chunk(" This is my third line using Chunk.");
doc.Add(paragraph);
doc.Add(pharse);
doc.Add(chunk);
doc.Close(); //Close document
Switch the filestream with a memorystream.
MemoryStream memStream = new MemoryStream();
PdfWriter wri = PdfWriter.GetInstance(doc, memStream);
...
return memStream.ToArray();
using iTextSharp.text;
using iTextSharp.text.pdf;
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
byte[] pdfBytes;
using(var mem = new MemoryStream())
{
using(PdfWriter wri = PdfWriter.GetInstance(doc, mem))
{
doc.Open();//Open Document to write
Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
Phrase pharse = new Phrase("This is my second line using Pharse.");
Chunk chunk = new Chunk(" This is my third line using Chunk.");
doc.Add(paragraph);
doc.Add(pharse);
doc.Add(chunk);
}
pdfBytes = mem.ToArray();
}
I've never used iTextPDF before but it sounded interesting so I took upon the challenge and did some research on my own. Here's how to stream the PDF document via memory.
protected void Page_Load(object sender, EventArgs e)
{
ShowPdf(CreatePDF2());
}
private byte[] CreatePDF2()
{
Document doc = new Document(PageSize.LETTER, 50, 50, 50, 50);
using (MemoryStream output = new MemoryStream())
{
PdfWriter wri = PdfWriter.GetInstance(doc, output);
doc.Open();
Paragraph header = new Paragraph("My Document") {Alignment = Element.ALIGN_CENTER};
Paragraph paragraph = new Paragraph("Testing the iText pdf.");
Phrase phrase = new Phrase("This is a phrase but testing some formatting also. \nNew line here.");
Chunk chunk = new Chunk("This is a chunk.");
doc.Add(header);
doc.Add(paragraph);
doc.Add(phrase);
doc.Add(chunk);
doc.Close();
return output.ToArray();
}
}
private void ShowPdf(byte[] strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now);
Response.BinaryWrite(strS);
Response.End();
Response.Flush();
Response.Clear();
}
Where your code has new FileStream, pass in a MemoryStream you've already created. (Don't just create it inline in the call to PdfWriter.GetInstance - you'll want to be able to refer to it later.)
Then call ToArray() on the MemoryStream when you've finished writing to it to get a byte[]:
using (MemoryStream output = new MemoryStream())
{
PdfWriter wri = PdfWriter.GetInstance(doc, output);
// Write to document
// ...
return output.ToArray();
}
I haven't used iTextSharp, but I suspect some of these types implement IDisposable - in which case you should be creating them in using statements too.

Categories