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();
}
}
}
Related
I have implemented the code but the problem is I am able to combine only one image into a single pdf but I want to combine multiple images into a single pdf. My code is:
public void ImagesToPdf(string[] imagepaths, string pdfpath)
{
using (var ms = new MemoryStream())
{
var srcImage = new Bitmap(imagepaths[0].ToString());
iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height);
var document = new iTextSharp.text.Document(pageSize, 0, 0, 0, 0);
iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression();
document.Open();
var image = iTextSharp.text.Image.GetInstance(imagepaths[0].ToString());
document.Add(image);
document.Close();
File.WriteAllBytes(pdfpath, ms.ToArray());
}
}
Any suggestions will be of great help. Thank you
I have finally figured out how to do this task.
public static byte[] ConvertIntoSinglePDF(List<string> filePaths)
{
Document doc = new Document();
doc.SetPageSize(PageSize.A4);
var ms = new System.IO.MemoryStream();
{
PdfCopy pdf = new PdfCopy(doc, ms);
doc.Open();
foreach (string path in filePaths)
{
byte[] data = File.ReadAllBytes(path);
doc.NewPage();
Document imageDocument = null;
PdfWriter imageDocumentWriter = null;
switch (Path.GetExtension(path).ToLower().Trim('.'))
{
case "bmp":
case "gif":
case "jpg":
case "png":
imageDocument = new Document();
using (var imageMS = new MemoryStream())
{
imageDocumentWriter = PdfWriter.GetInstance(imageDocument, imageMS);
imageDocument.Open();
if (imageDocument.NewPage())
{
var image = iTextSharp.text.Image.GetInstance(data);
image.Alignment = Element.ALIGN_CENTER;
image.ScaleToFit(doc.PageSize.Width - 10, doc.PageSize.Height - 10);
if (!imageDocument.Add(image))
{
throw new Exception("Unable to add image to page!");
}
imageDocument.Close();
imageDocumentWriter.Close();
PdfReader imageDocumentReader = new PdfReader(imageMS.ToArray());
var page = pdf.GetImportedPage(imageDocumentReader, 1);
pdf.AddPage(page);
imageDocumentReader.Close();
}
}
break;
case "pdf":
var reader = new PdfReader(data);
for (int i = 0; i < reader.NumberOfPages; i++)
{
pdf.AddPage(pdf.GetImportedPage(reader, i + 1));
}
pdf.FreeReader(reader);
reader.Close();
break;
default:
break;
}
}
if (doc.IsOpen()) doc.Close();
return ms.ToArray();
}
}
Once you got the byte array then just just write all bytes into file like this
byte[] document= ImagesToPDF.ConvertIntoSinglePDF(images);
File.WriteAllBytes("cheque.pdf", document);
ASP.NET C# Code Less
string FileNamePdf = PdfFileName.Text;
Document document = new iTextSharp.text.Document(PageSize.A4, 10f, 10f, 10f, 10f);
var output = new FileStream(Path.Combine(ObjData.ParentFolderPath + "\\SaveLocation", FileNamePdf + ".pdf"), FileMode.Create);
var writer = PdfWriter.GetInstance(document, output);
document.Open();
foreach (HttpPostedFile file in FilesToConvert.PostedFiles)
{
Image image = iTextSharp.text.Image.GetInstance(file.InputStream);
image.ScaleAbsolute(575f, 820.25f);
document.Add(image);
writer.NewPage();
}
document.Close();
I have been trying to add an image to all pages using iTextSharp.
According to this web page I need to look into the PdfPageEventHelper of iTextSharp.
It provides a method called OnEndPage that allows such things.
Basically, treat the image as being in the header or footer of the document, and use absolute positioning to put it where you want, instead of just in the flow of the page content.
The below code response with error :
Cannot access a non-static member of outer type 'System.Web.UI.Page'
via nested type 'PrintToPdf._events'
On :
PdfPCell cell2 = new PdfPCell(Image.GetInstance(Server.MapPath(imagepath)));
Is there any way to insert the image in the same way in all pages?
Can you help me ?
Thank you in advance.
class _events : PdfPageEventHelper
{
public override void OnEndPage(PdfWriter writer, Document document)
{
PdfPTable table = new PdfPTable(1);
table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
PdfPTable table2 = new PdfPTable(2);
string imagepath = #"Img\Logo.jpg";
PdfPCell cell2 = new PdfPCell(Image.GetInstance(Server.MapPath(imagepath)));
cell2.Colspan = 2;
table2.AddCell(cell2);
PdfPCell cell = new PdfPCell(table2);
table.AddCell(cell);
table.WriteSelectedRows(0, -1, document.LeftMargin, document.PageSize.Height - 36, writer.DirectContent);
}
}
private void PdfFiles()
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=test.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
pnPrint.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
string imagepath = #"Img\Logo.jpg";
Document pdfDoc = new Document(PageSize.A4, 20f, 20f, 10f, 20f);
try
{
_events e = new _events();
PdfWriter pw = PdfWriter.GetInstance(pdfDoc, new FileStream("test.pdf", FileMode.Create));
pw.PageEvent = e;
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
for (int i = 0; i < 5; i++)
{
Image image = Image.GetInstance(Server.MapPath(imagepath));
image.Alignment = Image.ALIGN_LEFT;
pdfDoc.Add(image);
htmlparser.Parse(sr);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
pdfDoc.Close();
Response.End();
}
}
Edit #1
protected class MyEvent : PdfPageEventHelper
{
Image image;
public override void OnOpenDocument(PdfWriter writer, Document document)
{
image = Image.GetInstance(#"C:\\intepub\\wwwroot\\img\\Logo.jpg");
image.SetAbsolutePosition(12, 300);
}
public override void OnEndPage(PdfWriter writer, Document document)
{
writer.DirectContent.AddImage(image);
}
}
// step 1
Document pdfDoc = new Document(PageSize.A4, 20f, 20f, 10f, 20f);
// step 2
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
MyEvent e = new MyEvent();
writer.PageEvent = e;
// step 3
pdfDoc.Open();
// step 4
pdfDoc.Add(new Paragraph("Hello World!"));
// step 5
pdfDoc.Close();
I merged two PDF files into one PDF file using iText Sharp . But is it possible to merge excel file into PDF file using iText Sharp also? i tried many times but it doesn't work for me.Here is my PDF Merge code:
protected void btnMerge_Click(object sender, EventArgs e)
{
if (file1.HasFile && file2.HasFile)
{
PdfReader pdfReader1 = new PdfReader(file1.PostedFile.InputStream);
PdfReader pdfReader2 = new PdfReader(file2.PostedFile.InputStream);
List<PdfReader> readerList = new List<PdfReader>();
readerList.Add(pdfReader1);
readerList.Add(pdfReader2);
//Define a new output document and its size, type
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
//Get instance response output stream to write output file.
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
foreach (PdfReader reader in readerList)
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
document.Add(iTextSharp.text.Image.GetInstance(page));
}
}
document.Close();
Response.AppendHeader("content-disposition", "inline; filename=OutPut.pdf");
Response.ContentType = "application/pdf";
}
}
private void MergePDFs(string outPutFilePath, params string[] filesPath)
{
List<PdfReader> readerList = new List<PdfReader>();
foreach (string filePath in filesPath)
{
PdfReader pdfReader = new PdfReader(filePath);
readerList.Add(pdfReader);
}
//Define a new output document and its size, type
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
//Create blank output pdf file and get the stream to write on it.
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outPutFilePath, FileMode.Create));
document.Open();
foreach (PdfReader reader in readerList)
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
document.Add(iTextSharp.text.Image.GetInstance(page));
}
}
document.Close();
}
}
}
I am using the following code to generate a PDF using iTextSharp from a GridView however the generated PDF is not visible to me. How can I view it in my html page?
GridView1.Visible = false;
SqlConnection sql = Connection.con();
sql.Open();
SqlCommand cmd = new SqlCommand("spGetSalesbyCustomer", sql);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CustomerId", Convert.ToInt32(TextBox1.Text));
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dd = new DataTable();
adp.Fill(dd);
GridView2.DataSource = dd;
GridView2.DataBind();
int cellCount = GridView2.Columns.Count;
sql.Close();
if (cellCount > 0)
{
GridView2.AllowPaging = false;
GridView2.DataBind();
BaseFont bf = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + #"\fonts\ARIALUNI.TTF", BaseFont.IDENTITY_H, true);
iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(cellCount);
int[] widths = new int[cellCount];
for (int x = 0; x < cellCount; x++)
{
widths[x] = (int)GridView2.Columns[x].ItemStyle.Width.Value;
string cellText = Server.HtmlDecode(GridView2.HeaderRow.Cells[x].Text);
//Set Font and Font Color
iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
//font.Color = new Color(GridView2.HeaderStyle.ForeColor);
iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));
//Set Header Row BackGround Color
//cell.BackgroundColor = new Color(GridView2.HeaderStyle.BackColor);
table.AddCell(cell);
}
table.SetWidths(widths);
for (int i = 0; i < GridView2.Rows.Count; i++)
{
if (GridView2.Rows[i].RowType == DataControlRowType.DataRow)
{
for (int j = 0; j < GridView2.Columns.Count; j++)
{
string cellText = Server.HtmlDecode(GridView2.Rows[i].Cells[j].Text);
//Set Font and Font Color
iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
//font.Color = new Color(GridView2.RowStyle.ForeColor);
iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));
//Set Color of row
if (i % 2 == 0)
{
//Set Row BackGround Color
//cell.BackgroundColor = new Color(GridView2.RowStyle.BackColor);
}
table.AddCell(cell);
}
}
}
//Create the PDF Document
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
int pages = pdfDoc.;
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
Your question is a little unclear but if your code is correct (and I know it isn't 100% based on the seventh last line) then you're not actually adding your PdfPTable to the Document:
//Create the PDF Document
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
//Bind a writer to our document abstraction and our output stream
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
//Open the document for writing
pdfDoc.Open();
//This next line is a syntax error
//int pages = pdfDoc.;
//Add the table to the PDF
pdfDoc.Add(table);
//Close the document
pdfDoc.Close();
//ASP.Net/HTTP stuff
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Do not use this next line, it doesn't do what you think it does
//Response.Write(pdfDoc);
Response.End();
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();
}
}