itext sharp generated pdf should open in new tab in mvc c# - c#

$(document).off("click", "#btnPreviewAndDownload").on("click", "#btnPreviewAndDownload", function (e) {
var QuestionPaperID = 1;
var SubjectCode = '#Model.Model.SubjectPapperCode';
window.location = "#Url.Action("PreviewAndDownloadQuestionPaper", "TeamCreation")?QuestionPaperID=" + QuestionPaperID + "&SubjectPapperCode=" + SubjectCode;
});
private FileResult CreateQuestionPaperPDF(List<CustomMainQuestionDTO> questionDTOList, byte[] byteDoc, MemoryStream memStream)
{
Document doc = new Document(iTextSharp.text.PageSize.A4, 70, 40, 70, 40);
PdfWriter writer = PdfWriter.GetInstance(doc, memStream);
Font fontH1 = new Font(Font.FontFamily.HELVETICA, 11, Font.BOLD);
doc.Open();
doc.NewPage();
Paragraph Heading = new Paragraph(questionDTOList[0].SubjectName, fontH4);
Heading.Alignment = Element.ALIGN_CENTER;
doc.Add(Heading);
foreach (var questionDTO in questionDTOList)
{
doc.Add(Chunk.NEWLINE);
if (String.IsNullOrEmpty(questionDTO.QuestionParentQuestionMappingID.ToString()))
{
MainQuestion(questionDTO, fontH2, doc, fontH1Bold);
}
else
{
SubQuestion(questionDTO, fontH2, fontH1, doc);
}
}
doc.Close();
byteDoc = memStream.GetBuffer();
string fileName = "QuestionPaper - " + questionDTOList[0].SubjectName + ".pdf";
return File(byteDoc, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
i have created and aligned the question paper format using Itextsharp and downloaded it.
it is downloading in window but unable to open in new tab? How i can open the generated PDF in new tab?

You can try using following code to generate your pdf it will display on your browser.
string filenm = "test";
Document doc = new Document(iTextSharp.text.PageSize.A4, 70, 40, 70, 40);
var fpath = Server.MapPath("~/PDFFiles/FunctionProspectus/");
PdfWriter.GetInstance(doc, new FileStream(fpath + filenm, FileMode.Create));
Font fontH1 = new Font(Font.FontFamily.HELVETICA, 11, Font.BOLD);
doc.Open();
doc.NewPage();
Paragraph Heading = new Paragraph("Test");
Heading.Alignment = Element.ALIGN_CENTER;
doc.Add(Heading);
doc.Add(Chunk.NEWLINE);
doc.Close();
string contentType = "application/pdf";
return File(Server.MapPath("~/PDFFiles/FunctionProspectus/") + filenm, contentType);
In one of my project i have used this and is working well.

If I'm reading the question correctly, you are able to create and return the PDF just fine, but it is causing the browser to navigate to the document instead of opening separately. The reason for this would be because you're changing window.location to the address of the action producing the PDF. One way to avoid this and simplify the code would be to use a hyperlink with the "target" attribute set to "_blank" instead of using JavaScript to open it. You could also use window.open instead of setting the location if you wanted to keep using the JavaScript solution. Both of these will either open in a new tab or new browser window depending on browser and user preference settings.

Related

c# save pdf file to specific path

I am using Visual Studio 2012. I am converting an aspx page into a PDF file.
It works fine...
the code is like this
string attachment = "attachment; filename=" + FileName + ".pdf";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/pdf";
StringWriter s_tw = new StringWriter();
HtmlTextWriter h_textw = new HtmlTextWriter(s_tw);
h_textw.AddStyleAttribute("font-size", "7pt");
h_textw.AddStyleAttribute("color", "Black");
pnlPrincipal.RenderControl(h_textw);//Name of the Panel
Document doc = new Document();
doc = new Document(PageSize.A4, 5, 5, 15, 5);
FontFactory.GetFont("Verdana", 80, iTextSharp.text.BaseColor.RED);
PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
StringReader s_tr = new StringReader(s_tw.ToString());
HTMLWorker html_worker = new HTMLWorker(doc);
html_worker.Parse(s_tr);
doc.Close();
Response.Write( doc);
The problem I am facing is that it is saved in c:/Users/Download folder.
I want to save the file in an specific folder.
Where can I specified that?
Thanks
You can write a document with
string folder = #"C:\Temp\";
string fileName = "mydocument.txt";
string fullPath = folder + fileName;
string data = "My string to write in a document";
File.WriteAllLines(fullPath, data);
// Read & print in console
string readText = File.ReadAllText(fullPath);
Console.WriteLine(readText);
Finally I found the way...
Instead of using Response I have to use FileStream
System.IO.FileStream fs = new FileStream(Server.MapPath("PDFDIR") + "\\" + otd.NumeroOTD.ToString() + ".pdf", FileMode.Create);
StringWriter s_tw = new StringWriter();
HtmlTextWriter h_textw = new HtmlTextWriter(s_tw);
h_textw.AddStyleAttribute("font-size", "7pt");
h_textw.AddStyleAttribute("color", "Black");
pnlPrincipal.RenderControl(h_textw);//Name of the Panel
// Create an instance of the document class which represents the PDF document itself.
Document document = new Document(PageSize.A4, 25, 25, 30, 30);
// Create an instance to the PDF file by creating an instance of the PDF
// Writer class using the document and the filestrem in the constructor.
FontFactory.GetFont("Verdana", 80, iTextSharp.text.BaseColor.RED);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.AddCreator("Sample application using iTextSharp");
document.AddSubject("Document subject - Describing the steps creating a PDF document");
document.AddTitle("The document title - PDF creation using iTextSharp");
// Open the document to enable you to write to the document
document.Open();
// Add a simple and wellknown phrase to the document in a flow layout manner
// document.Add(new Paragraph("Hello World!"));
StringReader s_tr = new StringReader(s_tw.ToString());
HTMLWorker html_worker = new HTMLWorker(document);
html_worker.Parse(s_tr);
// Close the document
document.Close();
// Close the writer instance
writer.Close();
// Always close open filehandles explicity
fs.Close();

getting text from a pdf document itextsharp

i tried using iTextSharp to get the text from a pdf document,
it works great if the pdf file is with english text(latin chars).
If i try to get the text from a pdf doc with cyrillic characters the output is just question marks. Are there some settings to be made, or cyrillic isnt supported?
this is the code for creating the pdf:
string testText = "зззi";
string tmpFile = #"C:\items\test.pdf";
string myFont = #"C:\windows\fonts\verdana.ttf";
iTextSharp.text.Rectangle pgeSize = new iTextSharp.text.Rectangle(595, 792);
iTextSharp.text.Document doc = new iTextSharp.text.Document(pgeSize, 10, 10, 10, 10);
iTextSharp.text.pdf.PdfWriter wrtr;
wrtr = iTextSharp.text.pdf.PdfWriter.GetInstance(doc,
new System.IO.FileStream(tmpFile, System.IO.FileMode.Create));
doc.Open();
doc.NewPage();
iTextSharp.text.pdf.BaseFont bfR;
bfR = BaseFont.CreateFont(myFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
iTextSharp.text.BaseColor clrBlack =
new iTextSharp.text.BaseColor(0, 0, 0);
iTextSharp.text.Font fntHead =
new iTextSharp.text.Font(bfR, 34, iTextSharp.text.Font.NORMAL, clrBlack);
iTextSharp.text.Paragraph pgr =
new iTextSharp.text.Paragraph(testText, fntHead);
doc.Add(pgr);
doc.Close();
this is the code for retrieving the text:
PdfReader reader1
= new PdfReader("c:/items/test.pdf");
Console.WriteLine(PdfTextExtractor.GetTextFromPage(reader1, 1, new SimpleTextExtractionStrategy()));
Console.ReadLine();
the output is: ???i
EDIT 2
i managed to read text from the pdf i created, but still cant get the text from a random pdf. How can i check if that pdf provides the required info for text extraction?

create multiple page pdf from asp.net mvc?

I was trying to create a pdf dynamically and send it by attaching in the mail.
This is my code and it works perfectly for me.
public ActionResult sendmail()
{
MemoryStream ms = new MemoryStream();
Document doc = new Document(PageSize.A4, 10f, 10f, 100f, 0.0f);
PdfWriter writer = PdfWriter.GetInstance(doc, ms);
doc.Open(); //open doc for editing
doc.Add(new Paragraph("First Paragraph"));
doc.Add(new Paragraph("Second Paragraph"));
writer.CloseStream = false; //important
doc.Close(); //build the doc.
ms.Position = 0;
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "provider.com";
smtpClient.Credentials = new NetworkCredential("credentialmailid", "password");
MailMessage mailMessage = new MailMessage()
{
From = new MailAddress("from#gmail.com")
};
mailMessage.To.Add(new MailAddress("to#gmail.com"));
mailMessage.Subject = "Pdf attached";
mailMessage.Attachments.Add(new Attachment(ms, "pdfname.pdf"));
smtpClient.Send(mailMessage);
return RedirectToAction("index");
}
Now my issue is : Document that I have to send is a purchase confirmation . it will have 3 pages. Many headings and styles will be there in it.
also some values I have to pass dynamically like who purchased it and date like wise a lot datas should pass dynamically
How to do this? I thought to create an Html of pdf file to be send and use something like this add parameters dynamically...
string mailpath = Server.MapPath("~/Mail/HtmlOF_pdfToSend.html");
string mailbody = System.IO.File.ReadAllText(mailpath);
mailbody = mailbody.Replace("##CompanyName", "Bhavin Merchant");
mailbody = mailbody.Replace("##BusinessType", "Bhavin business");
Fist You have to add iTextSharp dll then u have to add some packages :
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.xml;
using iTextSharp.text.html.simpleparser;
then as per your question. you want to pass dynamically values so i post some syntax as example :
// Create a Document object
var document = new Document(PageSize.A4, 50, 50, 25, 25);
var output = new MemoryStream();
// Create a new PdfWriter object, specifying the output stream
var writer = PdfWriter.GetInstance(document, output);
// Open the Document for writing
document.Open();
Suppose you have header in your pdf documnet so syntax will be :
var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/images/it.jpg"));
logo.SetAbsolutePosition(300, 750);
document.Add(logo);
If you want to add phrase:
Phrase titl = new Phrase("\nE-Ticket\n");
titl.Font.SetStyle(Font.BOLD);
document.Add(titl);
Add lines :
Phrase titl1 = new Phrase("--------------------------------------------------------------------------------------\n\n");
titl1.Font.SetStyle(Font.BOLD);
document.Add(titl1);
Change the style of text :
Here you can change the font style & color.
Phrase title = new Phrase("Booking Date-" + txtDate1.Text + "\n");
title.Font.SetStyle(Font.BOLD);
document.Add(title);
If you want to add pdf table:-dt is data table.
PdfPTable UserInfoTable = new PdfPTable(dt.Columns.Count);
PdfPRow row = null;
UserInfoTable.AddCell(--add cell----);
document.Add(UserInfoTable);
Close the Document - this saves the document contents to the output stream
document.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename=Receipt-{0}.pdf", "hello"));
Response.BinaryWrite(output.ToArray())
Here I paste some example code as your question.
You can add more pages to the document like this:
doc.Open(); //open doc for editing
doc.Add(new Paragraph("First Paragraph"));
doc.newPage();
doc.add(new Paragraph("This is a new page =)"));

MVC - Convert PdfPTable to Html

I am working on downloading a PDF document. I have used PdfPTable to create a table. Below is my shortened code.
var document = new Document(PageSize.A4, 50, 50, 25, 25);
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(document, output);
document.Open();
PdfPTable table = new PdfPTable(2);
table.WidthPercentage = 80;
PdfPCell cell = new PdfPCell(new Phrase("Description", fntTableFontBold));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
table.AddCell(cell);
......
document.Add(table);
document.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.pdf", "Journal"));
Response.BinaryWrite(output.ToArray());
All is working fine. Above code straight away downloads the PDF in browser.
Now i want to add Preview functionality, If the User clicks on Preview, He should see the HTML output.
How to convert this above code to show as HTML? There is lots of code & queries which are used for creating PdfPTable.
Creating a pdf using iTextSharp involves a lot of coding. You cannot render a pdf as HTML code (that I know of), but you can create an HTML first, convert it into a pdf and then render the pdf as stream to a browser. If you are creating the HTML first then you can use the html for preview.
Here is a block of code that I once wrote to convert html to pdf.
protected void ConvertHTMLToPDF(String HTMLCode, String fileName)
{
//Create PDF document
iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4);
PdfWriter.GetInstance(doc, new FileStream(HttpContext.Current.Server.MapPath("~") + "/Resources/Temp/" + fileName, FileMode.Create));
doc.Open();
foreach (IElement element in HTMLWorker.ParseToList(new StringReader(HTMLCode), null))
{
doc.Add(element);
}
doc.Close();
//Response.End();
}

PDF header doesnt get displayed Itextsharp

Hi I am writng some pdf by parsing html to it using itextsharp and it is working fine but I want to add page number on each every page of the pdf. for this I am adding header with dummy text in it(later I will replace it with page count) and writing dome content but the content is not displayed ..
try
{
Document oNewDocument = new Document(PageSize.A4, 20f, 20f, 30f, 10f);
PdfWriter.GetInstance(oNewDocument, new FileStream(pdfpath + "/" + sSaleInvoicePdf, FileMode.Create));
string content = "Some HTML Content";
List<IElement> parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), styles);
oNewDocument.AddHeader("text","text");
foreach (var htmlElement in parsedHtmlElements)
{
oNewDocument.Add(htmlElement as IElement);
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
oNewDocument.Close();
}
where I am worng. this code generate all the html content but not header text..??
Version 5+ you have to do this with a page event:
Handling header footer page event, itextsharp 5+
Before version 5 it works like:
Document oNewDocument = new Document(PageSize.A4, 20f, 20f, 30f, 10f);
PdfWriter.GetInstance(oNewDocument, new FileStream(pdfpath + "/" + sSaleInvoicePdf, FileMode.Create));
//Create some text to add to the header
Chunk text= new Chunk("my text");
Phrase phHeader = new Phrase();
phHeader.Add(text);
//Assign the Phrase to PDF Header
HeaderFooter header = new HeaderFooter(phHeader, false);
//Add the header to the document
oNewDocument.Header = header;
HeaderFooter hdr = new HeaderFooter(stringvalue, false);
hdr.Border = Rectangle.NO_BORDER;
hdr.Alignment = Element.ALIGN_LEFT;
doc.Header = hdr;
try this not sure whether your version supports this..give it a try

Categories

Resources