C# iTextSharp PdfCopy to MemoryStream copies entire document and single page - asp.net

I am trying to make a one page PDF from a 3 page PDF document using memory stream. But when the code below executes, all 3 pages get added and not just the first page.
What am I missing here? Please help.
Note: I am using iTextSharp v5.5.13
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
MemoryStream ms = new MemoryStream();
byte[] fileToBeEncrypted = null;
string sSourcePDF = "C:\\my3pageFile.pdf;
PdfReader pdfReader = new PdfReader(sSourcePDF);
Document document = new Document();
PdfCopy copy = new PdfCopy(document, ms) {CloseStream = false};
document.Open();
copy.AddPage(copy.GetImportedPage(pdfReader, iPage));
document.Close();
fileToBeEncrypted = ms.ToArray(); //returns the ENTIRE DOCUMENT AND NOT JUST PAGE 1
Can anyone help?
Thanks
Tom

The above code pdfCopy.GetImportedPages does works and I found an error further down in my own code.

Related

How to write text on different page based on text of exiting pdf using itextsharp

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
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...

Generate a PDF document from a webpage with style intact

I am using the iTextSharp library to convert a web page to a PDF document.
Although the document is successfully generated, the CSS applied on the webpage is not being applied in the PDF.
I take the HTML Markup and save it as a text file.
After that, I access that file and put the content into a string.
That markup gets converted in webpage and then into PDF.
But I am not able to apply any css to it.
Example Code:
using (MemoryStream stream = new MemoryStream())
{
Gridhtml = Gridhtml.Replace("\n", "").Replace("\r", "");
System.IO.File.WriteAllText(System.Web.HttpContext.Current.Server.MapPath("~/Content/HtmlTable/HtmlTableMarkup.txt"),Gridhtml);
StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath("~/Content/HtmlTable/HtmlTableMarkup.txt"));
Document pdfdoc = new Document(PageSize.A4,10f,10f,100f,0f);
PdfWriter pdfw = PdfWriter.GetInstance(pdfdoc,stream);
pdfdoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(pdfw,pdfdoc,sr);
pdfdoc.Close();
return File(stream.ToArray(), "applicationpdf", "Grid.pdf");
}
How can I obtain the PDF with the same styling as the webpage?

itextsharp PdfStamper.AcroFields.SetField giving error

I have a PDF containing Chinese, Japanese language. In that PDF I have some input fields. I want to fill this PDF dynamically in C#.net
I am using iTextSharp dll to read pad and successfully read the PDF fields but when I am going to set value with PdfStamper.AcroFields.SetField, it gives me this error
Font 'KozMinPro-Regular' with 'UniJIS-UCS2-H' is not recognized.
To read PDF and getting fields I am using the following code
string pdfTemplate = #"C:\Users\admin\Desktop\test.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
StringBuilder sb = new StringBuilder();
foreach (DictionaryEntry de in pdfReader.AcroFields.Fields)
{
sb.Append(de.Key.ToString() + Environment.NewLine);
}
And I am getting all fields successfully.
To fill data in PDF I am using this code
string pdfTemplate = #"C:\Users\admin\Desktop\test.pdf";
string newFile = #"C:\Users\admin\Desktop\newdata_test.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(
newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
// set form pdfFormFields
pdfFormFields.SetField("fill_17", "test");
I am facing error on pdfFormFields.SetField method as
Font 'KozMinPro-Regular' with 'UniJIS-UCS2-H' is not recognized.
Please advice what I have to change or how I can resolve this issue.
There are some files missing in your project. In order to use the font 'KozMinPro-Regular' with 'UniJIS-UCS2-H', you need to give iTextSharp access to the metrics files that contain information about that font. These metrics files can be downloaded separately from SourceForge. More specifically, you need the file iTextAsian-dll-2.1.zip that can be found in iTextAsian-all-2.1.zip
Note that this will only work with a recent version of iTextSharp (5.3.0.0 or higher). This iTextAsian DLL won't work with older versions of iTextSharp.

The document has no pages

I am using the below code to export gridview to PDF
form1.Controls.Clear();
form1.Controls.Add(GridView1);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
string html = "<html><body>" + sw.ToString() + "</body></html>";
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
Document document = new Document(PageSize.A4, 80, 50, 30, 65);
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
document.AddAuthor("Ram");
document.AddSubject("Export To pdf");
document.Open();
string tempFile = Path.GetTempFileName();
using (StreamWriter tempwriter = new StreamWriter(tempFile, false))
{
tempwriter.Write(html);
}
HtmlParser.Parse(document, tempFile);
document.Close();
writer.Close();
File.Delete(tempFile);
writer = null;
document = null;
Response.End();
I have checked that grridview has 10 rows by putting breakpoint. But I am getting error at
document.Close();
that
The document has no pages.
Any suggestion how to fix it?
1) Setting a breakpoint to see that your grid view has 10 rows helps, but only checks part of the problem. You also need to check the contents of tempFile. That's what iText is actually working with. If it's empty, you'll sill get the "doc has no pages" exception.
2.1) HtmlParser no longer exists within iText. Having said that, I just dug up this code sample via google:
public static void main(String[] args) throws Exception {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("html1.pdf"));
HtmlParser.parse(document, "example.html");
}
No opens or closes, just a call to HtmlParser. It's quite possible that HtmlParser checks to see if the document is already open, and won't proceed if it is... that would explain the behavior you're seeing.
2.2) The "correct" way to convert HTML these days goes something like this:
String html = readHtml();
List<Element> objects = HTMLWorker.parseToList(new StringReader(html), null);
for (Element element : objects)
document.add(element);
I had same issue and the below suggestion help and my issue is solved
Document has no pages means your GridView data is lost when you export.
Hence in the Export button event rebind the GridView with data from database
https://www.aspforums.net/Threads/264988/Export-GridView-to-PDF-Error-Document-has-no-pages/

What's the easiest way to convert a BMP to a PDF in ASP.net

What's the easiest way to convert a BMP file to a single page PDF using ASP.net? I'm going to generate the 8.5" x 11" BMP in Flash (which means I can manipulate it to make it as easy as possible), then use a POST to upload it to an ASP page, which will convert it to a PDF and redirect the user to the PDF. I don't want to add any margins or anything else, it will be laid out properly in the BMP for full-bleed.
Would it be easier to convert it to PDF in Flash, then upload?
Thanks!
You can use iTextSharp to create a PDF and insert the image into the document. This can be done all in memory with a final PDF produced to client.
The following is an MVC method, stripped for display, but should see how to do this.
[HttpGet]
public FileStreamResult Export(int? ID)
{
MemoryStream stream = new MemoryStream();
Document pdf = new Document();
PdfWriter writer = PdfWriter.GetInstance(pdf, stream);
pdf.Open();
PdfPTable tblImage = new PdfPTable(1);
tblImage.AddCell(Image.GetInstance(LogChart())); //The LogChart method returns image
pdf.Add(Image);
pdf.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Log.pdf");
Response.Buffer = true;
Response.Clear();
Response.OutputStream.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
return new FileStreamResult(Response.OutputStream, "application/pdf");
}

Resources