protected void txt_btn_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=TestResult.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringBuilder htmlText = new StringBuilder();
htmlText.Append("<table style='color:red;' border='1'><tr><th>createing pdf</th><tr><td> abcdef</td></tr></table>");
StringReader stringReader = new StringReader(htmlText.ToString());
Document doc = new Document(PageSize.A4);
List<iTextSharp.text.IElement> elements =
iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(stringReader, null);
doc.Open();
foreach (object item in elements)
{
doc.Add((IElement)item);
}
doc.Close();
// Response Output
PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
//doc.Close();
Response.Write("PDF is created");
}
}
I am try to create pdf file.But pdf is created only 0kb.Mean when i open this it's shw error that May be pdf damaged
I'm assuming that you are using iTextSharp library.
private void GeneratePDF()
{
try
{
string pdfPath = "~/PDF/File_1.pdf";
StringBuilder sb = new StringBuilder();
sb.Append("Name : chamara" + Environment.NewLine);
sb.Append("Address : sri lanaka" + Environment.NewLine);
sb.Append("Institute : SLIIT" + Environment.NewLine);
Document doc = new Document();
PdfWriter.GetInstance(doc, new FileStream(Server.MapPath(pdfPath), FileMode.Create));
doc.Open();
doc.Add(new Paragraph(sb.ToString()));
doc.Close();
}
catch (Exception ex)
{
throw ex;
}
}
Related
Can anyone tell me how can I create a pdf file using iTextSharp 7 and popup a save dialog instead of saving it to a specific disk location?
My test code is the following:
protected void btnPrint_OnClick(object sender, EventArgs e)
{
Document doc = new Document(PageSize.A4, 25f, 20f, 20f, 10f);
var output = new FileStream(Server.MapPath("MyFirstPDF.pdf"), FileMode.Create);
var writer = PdfWriter.GetInstance(doc, output);
doc.Open();
doc.Add(new Paragraph("test!"));
doc.Close();
}
The workaround I found is the following:
After creating the document:
string path = "C:\\...";
string fileName = "PdfFile.pdf";
FileInfo fileInfo = new FileInfo(path);
Byte[] FileBuffer = File.ReadAllBytes(fileInfo.FullName);
if (FileBuffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.AddHeader("content-length", FileBuffer.Length.ToString());
Response.BinaryWrite(FileBuffer);
Response.Flush();
//DELETE FILE AFTER DOWNLOAD
fileInfo.Delete();
Response.End();
}
hye, i have made this code which i have tried separately from my current web and it work perfectly but when i combine it with my web, i didn't get the output that was generated in the gridview. here is the code that i had used.
protected void Wordbtn_Click(object sender, EventArgs e)
{
if (maxdata.Checked == true)
{
wordmax();
}
if (curdata.Checked == true)
{
wordcur();
}
}
protected void excelbtn_Click(object sender, EventArgs e)
{
if (maxdata.Checked == true)
{
excelmax();
}
if (curdata.Checked == true)
{
excelcur();
}
}
protected void pdfbtn_Click(object sender, EventArgs e)
{
if (maxdata.Checked == true)
{
pdfmax();
}
if (curdata.Checked == true)
{
pdfcur();
}
}
public void wordmax()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=MaxdataExport.doc");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-word ";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridmaxdata.AllowPaging = false;
gridmaxdata.DataBind();
gridmaxdata.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public void wordcur()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=CurrentDataExport.doc");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-word ";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridcurdata.AllowPaging = false;
gridcurdata.DataBind();
gridcurdata.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public void excelmax()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=MaxDataExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridmaxdata.AllowPaging = false;
gridmaxdata.DataBind();
//Change the Header Row back to white color
gridmaxdata.HeaderRow.Style.Add("background-color", "#FFFFFF");
gridmaxdata.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public void excelcur()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=CurrentdataExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridcurdata.AllowPaging = false;
gridcurdata.DataBind();
//Change the Header Row back to white color
gridcurdata.HeaderRow.Style.Add("background-color", "#FFFFFF");
gridcurdata.RenderControl(hw);
//---------------------------------------------------------------------------------
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public void pdfmax()
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=MaxDataExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridmaxdata.AllowPaging = false;
gridmaxdata.DataBind();
gridmaxdata.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
public void pdfcur()
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=CurrentdataExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridcurdata.AllowPaging = false;
gridcurdata.DataBind();
gridcurdata.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
this is the code that i used to create the datagridview
public void maxdatatable()
{
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\inetpub\\wwwroot\\webradiation\\App_Data\\Radiation.mdf;Integrated Security=True;User Instance=True";
//Bind SQLDataSource to GridView for max data
// Create SQLDataSource.
SqlDataSource sqlDataSource1 = new SqlDataSource();
sqlDataSource1.ID = "SqlDataSource123";
this.Page.Controls.Add(sqlDataSource1);
// Bind ConnectionString to SQLDataSource.
sqlDataSource1.ConnectionString = connectionString;
// Retrieve records
sqlDataSource1.SelectCommand = "SELECT top 30 [date], [data] FROM [loc1] WHERE (([data] >= '2') AND (([date] >= '" + combdatetime11.ToString() + "') AND ([date] <= '" + combdatetime21.ToString() + "'))) ORDER BY [data] DESC, [date] DESC";
gridmaxdata.DataSource = sqlDataSource1;
gridmaxdata.DataBind();
}
public void currdata()
{
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\inetpub\\wwwroot\\webradiation\\App_Data\\Radiation.mdf;Integrated Security=True;User Instance=True";
// Create SQLDataSource.
SqlDataSource sqlDataSource2 = new SqlDataSource();
sqlDataSource2.ID = "SqlDataSource12";
this.Page.Controls.Add(sqlDataSource2);
// Bind ConnectionString to SQLDataSource.
sqlDataSource2.ConnectionString = connectionString;
// Retrieve records
sqlDataSource2.SelectCommand = "SELECT [date], [data] FROM [loc1] WHERE (([date] >= '" + combdatetime11.ToString() + "') AND ([date] < '" + combdatetime21.ToString() + "'))";
gridcurdata.DataSource = sqlDataSource2;
gridcurdata.DataBind();
}
for the word document, the output that i got is
(div) (/div)
*i have to used "(" and ")" to replace "<" and ">" because this pageweb make it disappear
the excel is like this
(style) .textmode { mso-number-format:\#; } (/style)(div)(div)
the pdf file i got an error saying that the document does not have pages.
do you not where did i do wrong?
you can create a extension function to convert the datasource datatable to excel and then send it to client using Response.WriteFile method
using OfficeOpenXml;
public static class Extensions
{
public static void ToExcel(this DataTable source, string destinationXlsxPath)
{
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Data");
ws.Cells["A1"].LoadFromDataTable(source, true);
FileInfo file = new FileInfo(destinationXlsxPath);
pck.SaveAs(file);
}
}
}
EPPlus: http://epplus.codeplex.com/
i have a database column 'images' which can hold binary data, for some reason the images doesnt want to upload. it doest pull any exceptions or aything wrong with the code:
here is extracts of the code
protected void BtnAdd_Click(object sender, EventArgs e)
{
string imgpath = FileUploadImage.FileName.ToString();
DBConnectivity.Add(imgpath);
}
here is the DBCoectivity Class:
public static void Add(string imgpath)
{
byte[] imgbt = null;
FileStream fstream = new FileStream(imgpath, FileMode.Open, FileAccess.Read);
BinaryReader BR = new BinaryReader(fstream);
imgbt = BR.ReadBytes((int)fstream.Length);
SqlConnection myConnection = GetConnection();
string myQuery = "INSERT INTO images( imagePath) VALUES ( #IMG )";
SqlCommand myCommand = new SqlCommand(myQuery, myConnection);
try
{
myConnection.Open();
myCommand.Parameters.Add(new SqlParameter("#IMG",imgbt));
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Exception in DBHandler", ex);
}
finally
{
myConnection.Close();
}
}
This snippet works for me:
byte[] imgbt = null;
if (FileUploadImage.HasFile)
{
Stream photoStream = FileUploadImage.PostedFile.InputStream;
imgbt = new byte[FileUploadImage.PostedFile.ContentLength];
photoStream.Read(imgbt, 0, FileUploadImage.PostedFile.ContentLength);
}
Also, you were inserting the image name (misspelled as parameter to Add method and bad choice of variable name as it is not a path) into the database, not the binary data. It should read:
string myQuery = "INSERT INTO images(imgbt) VALUES (#IMG)";
Here's a sample tutorial which explains it better:
File Upload with ASP.NET
I have rendered my aspx page to pdf successfully using ITextSharp.
Now i want to add watermark logo in background off PDF file please help me out i have been stuck into this.
Following is my code for export to pdf
private void ShowPdf(string s)
{
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=" + s);
Response.ContentType = "application/pdf";
Response.WriteFile(s);
Response.Flush();
Response.Clear();
}
public void PrepareControlForPDF()
{
MemoryStream mem = new MemoryStream();
StreamWriter twr = new StreamWriter(mem);
HtmlTextWriter myWriter = new HtmlTextWriter(twr);
divApplicantDetails.RenderControl(myWriter);
myWriter.Flush();
// myWriter.Dispose();
StreamReader strmRdr = new StreamReader(mem);
strmRdr.BaseStream.Position = 0;
string pageContent = strmRdr.ReadToEnd();
//CreatePDFDocument(strmRdr);
//strmRdr.Dispose();
///mem.Dispose();
CreatePDFDocument(pageContent);
//writer.Write(pageContent);
}
public void CreatePDFDocument(string strHtml)
{
string filename = ""+System.DateTime.Now.Day+"AppLetter.pdf";
// if (System.IO.File.Exists(Server.MapPath("../Pdf") + "/" + filename))
// {
// System.IO.File.Delete(Server.MapPath("../Pdf") + "/" + filename);
// }
string strFileName = Server.MapPath("../Pdf") + "/" + filename;
Document document = new Document();
try
{
PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
StringReader se = new StringReader(strHtml);
MemoryStream ms = new MemoryStream();
ms.Write(System.Text.Encoding.ASCII.GetBytes(strHtml), 0, System.Text.Encoding.ASCII.GetBytes(strHtml).Length);
//ms.Position = 0;
StreamReader sr = new StreamReader(new MemoryStream(new System.Text.ASCIIEncoding().GetBytes(strHtml)));
sr.BaseStream.Position = 0;
HTMLWorker obj = new HTMLWorker(document);
document.Open();
obj.Parse(se);
}
finally
{
document.Close();
}
}
I think you can achieve by creating a new class and implementing the IPdfPageEvent interface... refer here
I use Sharepoint 2010 and I am developing a web part where on a button click event, a pdf file needs to be generated and opened directly. Should not be saving onto the disk.
I tried the below code
protected void Button1_OnClick(object sender, EventArgs e)
{
Document myDoc = new Document(PageSize.A4.Rotate());
try
{
PdfWriter.GetInstance(myDoc, new FileStream(#"C:\Directory\Test.pdf", FileMode.Create));
myDoc.Open();
myDoc.Add(new Paragraph("Hello World"));
}
catch (DocumentException ex)
{
Console.Error.WriteLine(ex.Message);
}
myDoc.Close();
}
I also tried the below code which also generates the file on the Server which I dont want.
Document document = new Document(PageSize.A4);
PdfWriter.GetInstance(document, new FileStream(HttpContext.Current.Server.MapPath("~/Test.pdf"), FileMode.Create));
document.Open();
var WelcomePara = new Paragraph("Hello World");
document.Add(WelcomePara);
document.Close();
This one creates the pdf file on the desktop, I need it to be opened in the pdf format.Can someone help me please.
Almost every time that something accepts a FileStream is actually really accepts a generic System.IO.Stream object which FileStream is a subclass of. This means that you can instead use its cousin System.IO.MemoryStream which is what you are looking for:
byte[] bytes;
using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
using (iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate())) {
using (iTextSharp.text.pdf.PdfWriter w = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, ms)) {
doc.Open();
doc.NewPage();
doc.Add(new iTextSharp.text.Paragraph("Hello world"));
doc.Close();
bytes = ms.ToArray();
}
}
}
//Do whatever you want with the byte array here
You don't have to create the byte array if you don't want, I was just showing how to create a PDF and give you something ".net-like" for you to work with.
I was able to get it work finally.
using (var ms = new MemoryStream())
{
using (var document = new Document(PageSize.A4,50,50,15,15))
{
PdfWriter.GetInstance(document, ms);
document.Open();
document.Add(new Paragraph("HelloWorld"));
document.Close();
}
Response.Clear();
//Response.ContentType = "application/pdf";
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment;filename= Test.pdf");
Response.Buffer = true;
Response.Clear();
var bytes = ms.ToArray();
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.OutputStream.Flush();
}
This Works for me.
using (var ms = new MemoryStream())
{
using (var document = new Document(PageSize.A4,50,50,15,15))
{
// step 2
PdfWriter writer = PdfWriter.GetInstance(document, ms);
// step 3
document.Open();
// XML Worker
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
p.Parse(new StringReader(--Your HTML--));
// step 5
document.Close();
}
Byte[] FileBuffer = ms.ToArray();
if (FileBuffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", FileBuffer.Length.ToString());
Response.BinaryWrite(FileBuffer);
}
}