All the master, I have trouble about my gridview wich will export to PDF using iText and HtmForm .
I've browse on any sites, they suggest using HtmlForm and iText, but theres ways is enable for aspx not for webpart.
When I implement on my WebPart, the result export to pdf is to many code (I Mean thats code gernerated default of asp) .
this my code .
Page.Response.ContentType = "application/pdf";
Page.Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
HtmlForm frm = new HtmlForm();
MyGridView.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(MyGridView);
frm.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Page.Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Page.Response.Write(pdfDoc);
Page.Response.End();
And this is result export to pdf
//var theForm = document.forms['aspnetForm']; if (!theForm) { theForm = document.aspnetForm; } function
__doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit(); } } ////var MSOWebPartPageFormName = 'aspnetForm'; var g_presenceEnabled = true;
var g_wsaEnabled = false; var g_wsaQoSEnabled = false; var g_wsaQoSDataPoints = []; var g_wsaLCID =
1033; var g_wsaListTemplateId = 850; var g_wsaSiteTemplateId = 'BLANKINTERNET#0'; var ULS;if (!ULS)
ULS=new Object();ULS.enable=true;ULS.Correlation="f1edb09c-3170-50d3-ebe2-8970f486cf98";var
_fV4UI=true;var _spPageContextInfo = {webServerRelativeUrl: "\u002fsites\u002ffifpeduli", webAbsoluteUrl:
"http:\u002f\u002febiz4:8882\u002fsites\u002ffifpeduli", siteAbsoluteUrl:
"http:\u002f\u002febiz4:8882\u002fsites\u002ffifpeduli", serverRequestPath:
"\u002fsites\u002ffifpeduli\u002fPages\u002fBookingBusOperational.aspx", layoutsUrl: "_layouts\u002f15",
webTitle: "Bus Peduli", webTemplate: "53", tenantAppVersion: "0", webLogoUrl:
"_layouts\u002f15\u002fimages\u002fsiteicon.png", webLanguage: 1033, currentLanguage: 1033,
currentUICultureName: "en-US", currentCultureName: "en-US", clientServerTimeDelta: new Date("2014-08-22T07:50:45.8058752Z") - new Date(), siteClientTag: "35$$15.0.4569.1000",
crossDomainPhotosEnabled:false, webUIVersion:15,
webPermMasks:{High:432,Low:1011028719},pageListId:"{cda1b8fe-a191-40ae-9d5b-32845313a173}",pageItemId:31, pagePersonalizationScope:1,userId:161, systemUserKey:"i:0\u0029.w|s-1-5-21-3191234019-2725770046-3684772125-1119", alertsEnabled:false, siteServerRelativeUrl:
"\u002fsites\u002ffifpeduli", allowSilverlightPrompt:'True'};function CallServer_59082126(arg, context)
{WebForm_DoCallback('ctl00$ctl21',arg,SP.UI.MyLinksRibbon.MyLinksRibbonPageComponent.ribbonActio
nCallback,context,null,false); }function _myLinksRibbonLoad2() { var fnd = function () { try {
mylinks_init.MyLinksInit('CallServer_59082126'); } catch (Ex) { } }; RegisterSod('mylinks_init',
'/_layouts/15/SP.UI.MyLinksRibbon.js'); LoadSodByKey('mylinks_init', fnd); } function
_myLinksRibbonLoad1() { ExecuteOrDelayUntilScriptLoaded(_myLinksRibbonLoad2, 'SP.Ribbon.js'); }
_spBodyOnLoadFunctionNames.push('_myLinksRibbonLoad1'); var L_Menu_BaseUrl="/sites/fifpeduli"; var
L_Menu_LCID="1033"; var L_Menu_SiteTheme="null"; document.onreadystatechange=fnRemoveAllStatus;
function fnRemoveAllStatus(){removeAllStatus(true)};function WebForm_OnSubmit() {
UpdateFormDigest('\u002fsites\u002ffifpeduli', 1440000); return true; } //
No. FieldOne FieldTwo FieldThree FieldFour FieldFive
1 BEKASI 500.000
2 HEAD OFFICE 225.500 7.205.000 670.001 121.230.712
Total Result 225.500 7.205.000 670.001 121.730.712
//WebForm_InitCallback();var _spFormDigestRefreshInterval = 1440000;//
In real My pdf the table is real, sory before because can't upload image . because my reputations .
Please use below code.
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
private void GetInPDf()
{
if (gridview.Rows.Count > 0)
{
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gridview.RenderControl(htw);
var mem = new MemoryStream();
Document document = new Document(PageSize.LETTER, 50, 50, 50, 50);
PdfWriter.GetInstance(document, mem);
document.Open();
iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
hw.Parse(new StringReader(sw.ToString()));
document.Close();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now);
Response.BinaryWrite(mem.ToArray());
Response.End();
Response.Flush();
Response.Clear();
}
}
Related
I Created ExportToPDF Button to export Gridview to PDF file, then how can I add an image background as watermark to the PDF file?
protected void ExportToPDF(object sender, EventArgs e)
{
using (StringWriter sw = new StringWriter())
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
gvOrders.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
}
}
One solution would be;
private static Image watermark_600
{
get
{
if (_watermark_600 == null)
_watermark_600 = Image.FromFile(HttpContext.Current.Server.MapPath(#"~/content/Images/watermark600.png"));
return _watermark_600;
}
}
then,
public static byte[] AddWaterMark(byte[] fileContent)
{
if (fileContent == null)
return null;
//create a image object containing the photograph to watermark
using (var img = new ImageFactory())
using (var imgWatermark = new ImageLayer())
{
img.Load(fileContent);
if (img.Image.Width < 750 && img.Image.Height < 750)
imgWatermark.Image = (Image)watermark_200.Clone();
else if (img.Image.Width < 1500 && img.Image.Height < 1500)
imgWatermark.Image = (Image)watermark_400.Clone();
else if (img.Image.Width < 2500 && img.Image.Height < 2500)
imgWatermark.Image = (Image)watermark_600.Clone();
else
imgWatermark.Image = (Image)watermark_800.Clone();
int x = Math.Abs((img.Image.Width - imgWatermark.Image.Width)) / 2;
int y = Math.Abs((img.Image.Height - imgWatermark.Image.Height)) / 2;
imgWatermark.Position = new Point(x, y);
imgWatermark.Opacity = 90;
img.Overlay(imgWatermark);
using (MemoryStream msbyte = new MemoryStream())
{
img.Save(msbyte);
return msbyte.ToArray();
}
}
}
i am trying to pdf generate using html template in mvc4
and i have adding xmlworker packages and write a following code.
i will build my solution then show in following error.
XMLWorkerHelper does not contain a constructor that takes 0 arguments
Please suggest me...
Controller:-
public void abcd()
{
try
{
string UniqueNumber = Request.QueryString["UniqueNumber"];
string strFileName = UniqueNumber;
string strFileExtension = ".pdf";
string strContentType = FileManager.FileContentType_application_pdf;
string strExportData = string.Empty;
Document pdfDoc = new Document(PageSize.A4, 43f, 50f, 5f, 50f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
var output = new MemoryStream();
StringWriter sw = new StringWriter();
XMLWorkerHelper htw = new XMLWorkerHelper();
StringReader sr;
sr = new StringReader(Convert.ToString(ExportData.UserDetails(UniqueNumber)));
PdfWriter.GetInstance(pdfDoc, output);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
strFileName = strFileName.Replace(" - ", "-").Replace(" ", "-").Replace("--", "-");
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}{1}", strFileName, strFileExtension));
Response.ContentType = strContentType;
Response.Charset = "";
Response.BinaryWrite(output.ToArray());
Response.Flush();
Response.End();
}
catch (Exception ex)
{
//
}
}
It looks like the Singleton pattern is used within this assembly Dip.
Please replace your current code, XMLWorkerHelper htw = new XMLWorkerHelper(); with this XMLWorkerHelper htw = XMLWorkerHelper.GetInstance(); and give it a shot.
As a side note, you may want to look into the IDisposable interface. Check if any of the objects your are "newing" up implement it and dispose of them.
This one is driving me mad.
I'm trying to implement this example, which is working if you download the project, but I have a WebApi2 app, not the classic aspx, so I have problems with Response (The name 'Response' does not exist in the current context).
var document = new Document(PageSize.A4, 50, 50, 25, 25);
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(document, output);
document.Open();
document.Add(new Paragraph("Hello World"));
document.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename=testDoc.pdf", "some string"));
Response.BinaryWrite(output.ToArray());
I tried several things like adding HttpContext.Current to the Response like this:
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=testDoc.pdf", "some string"));
HttpContext.Current.Response.BinaryWrite(output.ToArray());
But there's no way I can make the .pdf document to show on/download from the browser.
What am I to do here?
With HttpResponseMessage:
public HttpResponseMessage ExampleOne()
{
var stream = CreatePdf();
return new HttpResponseMessage
{
Content = new StreamContent(stream)
{
Headers =
{
ContentType = new MediaTypeHeaderValue("application/pdf"),
ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "myfile.pdf"
}
}
},
StatusCode = HttpStatusCode.OK
};
}
With IHttpActionResult:
public IHttpActionResult ExampleTwo()
{
var stream = CreatePdf();
return ResponseMessage(new HttpResponseMessage
{
Content = new StreamContent(stream)
{
Headers =
{
ContentType = new MediaTypeHeaderValue("application/pdf"),
ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "myfile.pdf"
}
}
},
StatusCode = HttpStatusCode.OK
});
}
Here is the CreatePdf method:
private Stream CreatePdf()
{
using (var document = new Document(PageSize.A4, 50, 50, 25, 25))
{
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(document, output);
writer.CloseStream = false;
document.Open();
document.Add(new Paragraph("Hello World"));
document.Close();
output.Seek(0, SeekOrigin.Begin);
return output;
}
}
This is my working code. I need a little help with making this iterative as I am not familiar with itextsharp.
When I click Print button, it runs MySelectProcedure1 and table result is downloaded in a PDF named DataTable.
protected void btnPrint_Click(object sender, EventArgs e)
{
Procedure("MySelectProcedure1");.
Procedure("MySelectProcedure2");
}
protected void Procedure(string Proc)
{
Connection con = new Connection();
SqlDataAdapter da;
DataTable dt;
con.con = new SqlConnection(con.str);
con.cmd.CommandText = Proc;
con.cmd.CommandType = CommandType.StoredProcedure;
da = new SqlDataAdapter();
da.SelectCommand = con.cmd;
dt = new DataTable();
try
{
con.con.Open();
da.Fill(dt);
print(dt);
}
catch (Exception ex)
{
}
finally
{
con.con.Close();
con.con.Dispose();
}
}
protected void print (DataTable dt)
{
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=DataTable.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.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();
}
}
However, it does not print MySelectProcedure1 in the same PDF.
This is what I want:
Open PDF document.
Print a few lines
Print result of MySelectProcedure1
Print a few more lines
Print result of MySelectProcedure2
Close and Save PDF document
How do I do this?
Yok can create a public function for export PDF. I will write how i use it.
Create a public class for example general.cs. And add this code in it.
public static void ExportPDF(DataTable dt1, DataTable dt2)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.pdf", "PDFExport"));
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
//For First DataTable
System.IO.StringWriter stringWrite1 = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite1 = new HtmlTextWriter(stringWrite1);
DataGrid myDataGrid1 = new DataGrid();
myDataGrid1.DataSource = dt1;
myDataGrid1.DataBind();
myDataGrid1.RenderControl(htmlWrite1);
//For Second DataTable
System.IO.StringWriter stringWrite2 = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite2 = new HtmlTextWriter(stringWrite2);
DataGrid myDataGrid2 = new DataGrid();
myDataGrid2.DataSource = dt2;
myDataGrid2.DataBind();
myDataGrid2.RenderControl(htmlWrite2);
//You can add more DataTable
StringReader sr = new StringReader(stringWrite1.ToString() + stringWrite2.ToString());
Document pdfDoc = new Document(new Rectangle(288f, 144f), 10f, 10f, 10f, 0f);
pdfDoc.SetPageSize(PageSize.A4.Rotate());
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
HttpContext.Current.Response.Write(pdfDoc);
HttpContext.Current.Response.End();
}
When you need PDF only call this function
protected void lnkExportPDF_Click(object sender, EventArgs e)
{
General.ExportPDF(rptList);
}
public override void VerifyRenderingInServerForm(Control control)
{ }
I'm working on a asp.Net project where it requires to save in as pdf. I need to create a Label and a TextBox dynamically based on the data present in the database.
My problem is that when I try to save it in pdf,only Labels can be saved while the TextBox goes missing.
Below is my code for creating Label & TextBox dynamically.
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox txtSkills = new TextBox();
TextBox txtProficiency = new TextBox();
Label lblSkills = new Label();
Label lblProficiency = new Label();
txtSkills.ID = "txtSkills" + i.ToString();
txtSkills.Text = dt.Rows[i].ItemArray[1].ToString();
txtProficiency.ID = "txtProficiency" + i.ToString();
txtProficiency.Text = dt.Rows[i].ItemArray[2].ToString();
lblSkills.ID = "lblSkills" + i.ToString();
lblSkills.Text = "Skills:";
lblProficiency.ID = "lblProficiency" + i.ToString();
lblProficiency.Text = "Proficiency:";
Panel3.Controls.Add(lblSkills);
Panel3.Controls.Add(txtSkills);
Panel3.Controls.Add(lblProficiency);
Panel3.Controls.Add(txtProficiency);
Code for saving in pdf :-
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" somename ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
Panel3.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
Paragraph p1 = new Paragraph();
p1.SpacingAfter = 15f;
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
pdfDoc.Add(new Paragraph("Education"));
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();