while export to pdf using itexsharp it shows blank page - asp.net

i made one desktop application using asp.net which convert html to PDF.
basically this application used for generate users PDF from database.
process: first of all i am converting all data to html and then convert to PDF using itextsharp but after generating some PDFs it shows blank pages
any idea or anyone face this type of issue
public static void converttopdf(string HtmlStream, List<Tuple<string, string>> tifffiles, List<Tuple<string, string>> pdffilestomerge, string filename, string patientfirstpagestr, string TableofContent, string patientheader, SqlConnection con, string sectiondetails)
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(HtmlStream);
Document document = new Document(PageSize.A4, 30, 30, 42, 44);
string filetogenerate = string.Empty;
if (pdffilestomerge != null && pdffilestomerge.Count > 1)
{
filetogenerate = temppath + filename + "_Temp1.pdf";
}
else
{
filetogenerate = temppath + filename + "_Temp.pdf";
}
PdfWriter writer = PdfWriter.GetInstance(document, new System.IO.FileStream(filetogenerate, System.IO.FileMode.Create));
HTMLWorker worker = new HTMLWorker(document);
document.Open();
worker.StartDocument();
string[] separator = new string[] { #"<br clear='all' style='page-break-before:always'>" };
string[] pages = HtmlStream.Split(separator, StringSplitOptions.None);
foreach (string page in pages)
{
document.NewPage();
System.Collections.ArrayList htmlarraylist = HTMLWorker.ParseToList(new StringReader(page), null);
for (int k = 0; k < htmlarraylist.Count; k++)
{
document.Add((IElement)htmlarraylist[k]);
}
}
using (var ms = new MemoryStream())
{
if (tifffiles != null)
{
int docid = 0;
foreach (var obj in tifffiles)
{
string filepath = obj.Item2.ToString();
WriteLogEntry("bitmap file path : " + filepath);
if (filepath != string.Empty)
{
try
{
Bitmap myBitmap = new Bitmap(filepath);
System.Drawing.Color pixelColor = myBitmap.GetPixel(50, 50);
if (pixelColor.Name == "ff808080")
{
WriteLogEntry("convert image by irfanview :" + filepath);
LaunchCommandLineApp(filepath, temppath + "Test.jpg");
document.NewPage();
var imgStream = GetImageStream(temppath + "Test.jpg");
var image = iTextSharp.text.Image.GetInstance(imgStream);
image.SetAbsolutePosition(10, 80);
image.ScaleToFit(document.PageSize.Width - 60, document.PageSize.Height - 80);
//image.ScaleToFit(document.PageSize.Width - 30, document.PageSize.Height);
if (docid != Convert.ToInt32(obj.Item1))
{
Chunk c1 = new Chunk("#~#DID" + obj.Item1.ToString() + "#~#");
c1.Font.SetColor(0, 0, 0); //#00FFFFFF
c1.Font.Size = 0;
document.Add(c1);
}
document.Add(image);
File.Delete(temppath + "Test.jpg");
}
else
{
document.NewPage();
var imgStream = GetImageStream(filepath);
var image = iTextSharp.text.Image.GetInstance(imgStream);
image.SetAbsolutePosition(10, 80);
image.ScaleToFit(document.PageSize.Width - 60, document.PageSize.Height - 80);
//image.ScaleToFit(document.PageSize.Width - 30, document.PageSize.Height);
if (docid != Convert.ToInt32(obj.Item1))
{
Chunk c1 = new Chunk("#~#DID" + obj.Item1.ToString() + "#~#");
c1.Font.SetColor(0, 0, 0); //#00FFFFFF
c1.Font.Size = 0;
document.Add(c1);
}
document.Add(image);
WriteLogEntry("Image added successfully" + filepath);
}
}
catch
{
document.NewPage();
if (docid != Convert.ToInt32(obj.Item1))
{
Chunk c1 = new Chunk("#~#DID" + obj.Item1.ToString() + "#~#");
c1.Font.SetColor(0, 0, 0); //#00FFFFFF
c1.Font.Size = 0;
document.Add(c1);
}
WriteLogEntry("Image not valid" + filepath);
}
docid = Convert.ToInt32(obj.Item1);
}
}
}
}
worker.EndDocument();
worker.Close();
document.Close();
if (pdffilestomerge != null && pdffilestomerge.Count > 1)
{
string file = temppath + filename + "_Temp.pdf";
mergepdf(file, pdffilestomerge, filetogenerate);
}
PdfReader pdfreader = new PdfReader(temppath + filename + "_Temp.pdf");
Document document1 = new Document(PageSize.A4, 30, 30, 42, 44);
PdfWriter writer1 = PdfWriter.GetInstance(document1, new FileStream(FinalOutputPath + filename + ".pdf", FileMode.Create));
//HeaderFooter footer = new HeaderFooter(new Phrase("Page "), true);
//footer.Alignment = Element.ALIGN_RIGHT;
//footer.Border = iTextSharp.text.Rectangle.NO_BORDER;
//document1.Footer = footer;
//HeaderFooter header = new HeaderFooter(new Phrase(""), true);
//header.Alignment = Element.ALIGN_LEFT;
//header.Border = iTextSharp.text.Rectangle.NO_BORDER;
//document1.Add(header);
document1.Open();
PdfContentByte cb1 = writer1.DirectContent;
PdfImportedPage page1;
string test1 = TableofContent; int TableofContentPageCount = 0; int SectionPageStartNumber = 0;
string lastdocnamestr = "";
for (int t = 1; t <= pdfreader.NumberOfPages; t++)
{
document1.NewPage();
HeaderFooter header = new HeaderFooter(new Phrase(""), true);
header.Alignment = Element.ALIGN_LEFT;
header.Border = iTextSharp.text.Rectangle.NO_BORDER;
HeaderFooter header1 = new HeaderFooter(new Phrase(" "), true);
header1.Alignment = Element.ALIGN_LEFT;
header1.Border = iTextSharp.text.Rectangle.NO_BORDER;
HeaderFooter header2 = new HeaderFooter(new Phrase(" "), true);
header2.Alignment = Element.ALIGN_LEFT;
header2.Border = iTextSharp.text.Rectangle.NO_BORDER;
document1.Add(header);
document1.Add(header1);
document1.Add(header2);
page1 = writer1.GetImportedPage(pdfreader, t);
var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
byte[] pdfcontent = pdfreader.GetPageContent(t);
//PdfDictionary dict = pdfreader.GetPageN(t);
string contentStream = System.Text.Encoding.Default.GetString(pdfcontent);
var contentByte = writer1.DirectContent;
contentByte.BeginText();
contentByte.SetFontAndSize(baseFont, 8);
var multiLineString = "";
var multiLineString1 = "";
string test = getBetween(contentStream, "#~#", "#~#");
if (test.Length > 0)
{
test1 = test1.Replace(test + ".", t.ToString());
DataTable dt = getdocdetailforheader(Convert.ToInt32(test.Replace("DID", "")), con);
if (dt.Rows.Count > 0)
{
multiLineString = dt.Rows[0]["DocumentName"].ToString() + " - " + Convert.ToDateTime(dt.Rows[0]["EncounterDTTM"].ToString()).ToString("MM/dd/yyyy") + " | Owner : " + dt.Rows[0]["Ownername"].ToString();
lastdocnamestr = multiLineString;
WriteLogEntry(multiLineString);
}
if (TableofContentPageCount == 0)
{
TableofContentPageCount = t;
}
}
//if (contentStream.Contains("sectionstart") && SectionPageStartNumber == 0) SectionPageStartNumber = t;
if (lastdocnamestr != string.Empty)
{
multiLineString = lastdocnamestr;
}
//else
//{
// if (TableofContentPageCount == 0)
// {
// multiLineString = "Table of Content";
// }
//}
multiLineString1 = patientheader;
contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, multiLineString, 15, 820, 0);
contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, multiLineString1, 15, 810, 0);
contentByte.EndText();
string relLogo = Directory.GetCurrentDirectory().ToString().Replace("bin", "").Replace("Debug", "").Replace("\\\\", "") + "\\Image\\MFA_LOGO.png";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(relLogo);
jpg.ScaleAbsolute(38f, 38f);
jpg.SetAbsolutePosition(document1.PageSize.Width - 70, 806);
jpg.Alignment = Element.ALIGN_RIGHT;
document1.Add(jpg);
cb1.MoveTo(0, 805);
cb1.LineTo(document1.PageSize.Width, 805);
cb1.Stroke();
cb1.AddTemplate(page1, 0, 0);
}
SectionPageStartNumber = pdfreader.NumberOfPages + 1;
System.Collections.ArrayList htmlarraylist1 = HTMLWorker.ParseToList(new StringReader(sectiondetails), null);
document1.NewPage();
for (int k = 0; k < htmlarraylist1.Count; k++)
{
document1.Add((IElement)htmlarraylist1[k]);
}
document1.Close();
FinalPDF(FinalOutputPath + filename + ".pdf", FinalOutputPath + filename + "_1.pdf", patientfirstpagestr, test1, TableofContentPageCount, patientheader, SectionPageStartNumber);
File.Delete(temppath + filename + "_Temp.pdf");

Related

How to insert a picture into a word processing document using DocumentFormat.OpenXML Library and AltChunk Class c#

I am using Telerik:RadEditor component for Asp.Net to save openXML and html report, I need to download word file format from this html report using DocumentFormat.OpenXML library from Microsoft, the code i used working successfully but can't see image after download word file.
I tried the below references but image not showing also.
https://learn.microsoft.com/en-us/office/open-xml/how-to-insert-a-picture-into-a-word-processing-document
https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.wordprocessing.altchunk?view=openxml-2.8.1
Add HTML String to OpenXML (*.docx) Document
How to insert a non-inline picture into a word document using VB6?
Adding image in word document
My Code is as follows:
protected void btnsavetoword_Click(object sender, EventArgs e)
{
try
{
clsReportTemplateBO objexist = new clsReportTemplateBO();
objexist.RefNo = hdnRefNo.Value;
objexist.CreatedBy = clsUser.UserName;
List<clsReportTemplateBO> objReport = clsReportTemplateBL.GetSavedReports(objexist);
if (objReport.Count > 0)
{
string ReportText = edrReport.Content;
ReportText = ReportText.Replace(objReport[0].HeaderHTML, "");
ReportText = ReportText.Replace(objReport[0].FooterHTML, "");
objexist.ReportCode = objReport[0].ReportCode;
foreach (clsReportTemplateBO datarow in objReport)
{
if (datarow.ReportFormat == "Word")
{
objexist.PatientReportId = datarow.PatientReportId;
}
}
if (objReport.Count == 2)
{
string PatientReportId = objexist.PatientReportId;
ConverttoWord(objexist.ReportCode, PatientReportId, ReportText);
rdWMngr.RadAlert("Report saved successfully", 400, 150, "Report", null, clsConstants.SucccessMessage);
}
else if (objReport.Count == 1 && objReport[0].ReportFormat == "HTML")
{
objexist.ReportName = objReport[0].ReportName;
objexist.HID = objReport[0].HID;
objexist.CreatedBy = clsUser.UserName;
objexist.ReportFormat = "Word";
objexist.RefNo = hdnRefNo.Value;
if (clsReportTemplateBL.SavePatientReport(objexist))
{
string PatientReportId = objexist.PatientReportId;
ConverttoWord(objexist.ReportCode, PatientReportId, ReportText);
rdWMngr.RadAlert("Report saved successfully", 400, 150, "Report", null, clsConstants.SucccessMessage);
}
}
else if (objReport.Count == 1 && objReport[0].ReportFormat == "Word")
{
string PatientReportId = objexist.PatientReportId;
ConverttoWord(objexist.ReportCode, PatientReportId, ReportText);
rdWMngr.RadAlert("Report saved successfully", 400, 150, "Report", null, clsConstants.SucccessMessage);
}
}
else
{
clsReportTemplateBO obj = new clsReportTemplateBO();
string ReportCode = HttpContext.Current.Session["ReportCode"].ToString();
obj = clsReportTemplateBL.GetReportTemplate(ReportCode);
obj.ReportName = ReportName;
obj.ReportCode = ReportCode;
obj.HID = HID;
obj.CreatedBy = clsUser.UserName;
obj.ReportFormat = "Word";
obj.RefNo = hdnRefNo.Value;
string ReportText = edrReport.Content;
ReportText = ReportText.Replace(obj.HeaderHTML, "");
ReportText = ReportText.Replace(obj.FooterHTML, "");
if (clsReportTemplateBL.SavePatientReport(obj))
{
string PatientReportId = obj.PatientReportId;
ConverttoWord(ReportCode, PatientReportId, ReportText);
rdWMngr.RadAlert("Report saved successfully", 400, 150, "Report", null, clsConstants.SucccessMessage);
}
}
}
catch
{
rdWMngr.RadAlert("Report saved failed", 400, 150, "Report", null, clsConstants.ErrorMessage);
}
}
ConvertToWord method as follows:
protected void ConverttoWord(string ReportCode, string PatientReportId, string ReportText)
{
string domain = HttpContext.Current.Request.Url.Authority;
string RefNo = hdnRefNo.Value;
int PatientReportDetailId = clsReportTemplateBL.SavePatientReportDetail(PatientReportId, RefNo, domain, clsUser.UserName);
string sourceFile = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ReportFormatPath"].ToString() + ReportCode + ".docx");
string destFile = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["SavedReportPath"].ToString() + RefNo + PatientReportDetailId.ToString() + ".docx");
System.IO.FileInfo file = new System.IO.FileInfo(sourceFile);
System.IO.FileInfo dest = new System.IO.FileInfo(destFile);
if (file.Exists)
{
if (dest.Exists)
{
rdWMngr.RadAlert("File already converted. Try to download from Saved Report", 400, 150, "Saved Report", null, clsConstants.WarningMessage);
}
else
{
File.Copy(sourceFile, destFile);
}
exporttoword(destFile, ReportText);
}
else
{
rdWMngr.RadAlert("File not exist on " + sourceFile, 400, 150, "Saved Report", null, clsConstants.WarningMessage);
}
}
ExportToWord method as follows:
private void exporttoword(string FilePath, string ReportText)
{
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(FilePath, true))
{
string altChunkId = "AltChunkId1";
MainDocumentPart mainPart = myDoc.MainDocumentPart;
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart("application/xhtml+xml"/*AlternativeFormatImportPartType.Html*/, altChunkId);
//string stamp = "~/images/Menu/EStamp.png"; //Location of image that I need to insert into word when i save
using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
{
using (StreamWriter streamWriter = new StreamWriter(chunkStream))
{
streamWriter.Write(ReportText);
}
}
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
// this inserts altChunk after the last Paragraph
mainPart.Document.Body
.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
mainPart.Document.Save();
}
//Download
System.IO.FileInfo file = new System.IO.FileInfo(FilePath);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
rdWMngr.RadAlert("Error", 400, 150, "Saved Report", null, clsConstants.WarningMessage);
}
}
How can I insert image to the word file when I need to download it using DocumentFormat.OpenXML library in Asp.Net?

I am working with asp.net and i try to display multiple div dynamically it working but every time display same slider data

#region fillAllData4
private void fillAllData4()
{
clsCategory objCategory = new clsCategory(true);
clsProductMain objProduct = new clsProductMain(true);
objCategory.getDropDownMenu();
objProduct.getProduct();
string str = string.Empty;
int i = 0;
// int j = 0;
if (objCategory.ListclsCategory.Count > 0)
{
for (i = 0; i < objCategory.ListclsCategory.Count; i++)
{
cat.InnerHtml = objCategory.ListclsCategory[0].CategoryName;
cat1.InnerHtml = objCategory.ListclsCategory[1].CategoryName;
cat2.InnerHtml = objCategory.ListclsCategory[2].CategoryName;
cat3.InnerHtml = objCategory.ListclsCategory[3].CategoryName;
string[] filePaths = Directory.GetFiles(Server.MapPath("~/images/Saree/"));
int j = 0;
foreach (string filePath in filePaths)
{
string fileName = Path.GetFileName(filePath);
str += #"<div><div><img class='imges' src='images/Saree/" + fileName + #"' /></div>
<div class='sname'>" + objProduct.ListclsProductMain[j].ProductName + #"</div>
<div class='sname2'>" + objProduct.ListclsProductMain[j].MRP + #"</div></div>";
j++;
}
slider3.InnerHtml = str;
slider4.InnerHtml = str;
slider5.InnerHtml = str;
slider6.InnerHtml = str;
//System.Web.UI.HtmlControls.HtmlGenericControl createDiv =
//new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
//createDiv.ID = "createDiv";
//createDiv.InnerHtml =str;
//this.Controls.Add(createDiv);
}
}
}
#endregion

How to write two Handlers using Switch Case

i wrote two handlers but i need to write now only one handler using switch case how to write i tried but not working. please help me. this is my two handlers code i want that in switch case.please solve this problem
public void ProcessRequest(HttpContext context)
{
string fname = string.Empty;
string ffname = string.Empty;
string m_Result = string.Empty;
DataTable dt = new DataTable();
Guid id = Guid.NewGuid();
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
ffname = "~/Adds_uploads/" + fname;
}
string p = Path.GetFileNameWithoutExtension(fname);
fname = Path.Combine(context.Server.MapPath("~/Adds_uploads/"), p);
file.SaveAs(fname + id + Path.GetExtension(ffname));
string dirName1 = new DirectoryInfo(fname).Name;
FileInfo fInfo = new FileInfo(ffname);
String dirName = fInfo.Directory.Name + '/' + dirName1 + id + Path.GetExtension(ffname);
HttpContext.Current.Response.Write(JsonConvert.SerializeObject(dirName));
//RAID = context.Request.QueryString["RA_ID"].ToString();
//UploadFileToDB(file, RAID);
}
}
}
public bool IsReusable {
get {
return false;
}
}
2nd Handler
public void ProcessRequest(HttpContext context)
{
string fname = string.Empty;
string ffname = string.Empty;
string m_Result = string.Empty;
DataTable dt = new DataTable();
Guid id = Guid.NewGuid();
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
ffname = "~/Fileuploads/" + fname;
}
string p = Path.GetFileNameWithoutExtension(fname);
fname = Path.Combine(context.Server.MapPath("~/Fileuploads/"), p);
file.SaveAs(fname + id + Path.GetExtension(ffname));
string dirName1 = new DirectoryInfo(fname).Name;
FileInfo fInfo = new FileInfo(ffname);
String dirName = fInfo.Directory.Name + '/' + dirName1 + id + Path.GetExtension(ffname);
HttpContext.Current.Response.Write(JsonConvert.SerializeObject(dirName));
//RAID = context.Request.QueryString["RA_ID"].ToString();
//UploadFileToDB(file, RAID);
}
}
}
public bool IsReusable {
get {
return false;
}
}
I think the only difference if the upload path. I would suggest you to pass along another input form the view and then determine the upload path based on that.
i.e
you would have
//for case one
<input type='hidden' name='uploadType' value='files' />
//for case two
<input type='hidden' name='uploadType' value='adds' />
inside your individual file upload forms and then on your action method you can just use
var mappedDirectory = HttpContext.Current.Request.Form["uploadType"].ToString() == "adds" ? "~/Adds_uploads/" : "~/Fileuploads/";
and use this string in your fname construct. So your new method would be like
public void ProcessRequest(HttpContext context)
{
var mappedDirectory = HttpContext.Current.Request.Form["uploadType"].ToString() == "adds" ? "~/Adds_uploads/" : "~/Fileuploads/";
string fname = string.Empty;
string ffname = string.Empty;
string m_Result = string.Empty;
DataTable dt = new DataTable();
Guid id = Guid.NewGuid();
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
ffname = mappedDirectory + fname;
}
string p = Path.GetFileNameWithoutExtension(fname);
fname = Path.Combine(context.Server.MapPath(mappedDirectory), p);
file.SaveAs(fname + id + Path.GetExtension(ffname));
string dirName1 = new DirectoryInfo(fname).Name;
FileInfo fInfo = new FileInfo(ffname);
String dirName = fInfo.Directory.Name + '/' + dirName1 + id + Path.GetExtension(ffname);
HttpContext.Current.Response.Write(JsonConvert.SerializeObject(dirName));
//RAID = context.Request.QueryString["RA_ID"].ToString();
//UploadFileToDB(file, RAID);
}
}
}

Java servlet - export to an excell using string buffer

I am new to JAVA. I am trying to export Excel through servlet from resultset.
When i am trying to store data in String buffer the it is not actually saving it.
Testfirst.java
String assingee_name = req.getParameter("firstName");
String track_name = req.getParameter("track");
String sla_id = req.getParameter("sla");
StringBuffer sb = new StringBuffer();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Databasethree");
stmt = con.createStatement();
//pw.println("'" +assingee_name + "'");
length = track_name.length();
if (length > 0) {
rs = stmt.executeQuery("SELECT* FROM casedetails where track =" + "'" + track_name + "'");
}
length = sla_id.length();
if (length > 0) {
//rs = stmt.executeQuery("SELECT* FROM casedetails where case_age >"+"'" +sla_id + "'");
rs = stmt.executeQuery("SELECT* FROM cdoscase where Incident_Submit_Fiscal_Year=" + "'" + sla_id + "'");
}
length = assingee_name.length();
if (length > 0) {
rs = stmt.executeQuery("SELECT* FROM casedetails where Assingee_name =" + "'" + assingee_name + "'");
}
pw.println("<html><body>");
pw.println("<H1> CDOS Case Management Version 1.1 </H1>");
pw.println("<Head><style>table,th,td{border:1px solid black;}</style></head>");
pw.println("<table>");
ResultSetMetaData rm = rs.getMetaData();
int clm = rm.getColumnCount();
StringBuffer sb1 = new StringBuffer();
String sb2 = new String();
for (int j = 1; j <= clm; j++) {
sb2 = rm.getColumnName(j);
pw.println("<th>");
pw.println(sb2);
pw.println("</th>");
}
ArrayList Rows = new ArrayList();
ArrayList row = new ArrayList();
Object a = new Object();
int jj = 0; // to find out the number rows
while (rs.next()) {
jj = jj + 1;
pw.println("<tr>");
for (int i = 1; i <= clm; i++) {
//data1[i]=rs.getString(i);
pw.println("<td>");
//pw.println(rs.getObject(i).toString());
pw.println(rs.getString(i));
pw.println("</td>");
sb2.append(rs.getString(i);
//row.add(rs.getString(i));
//sb2=sb2+rs.getObject(i).toString();
}
pw.println("</tr>");
} sb1.append("fd");
//Rows.add(row);
pw.println("Total Records found" + sb1);
pw.println("</table>");
//sb2=sb2+rs.getObject(clm).toString();
//sb1.append(sb2);
//sb1.append(sb2);
a = rs.getString(4).toString();
pw.println("this is data " + a);
pw.println("<p>");
pw.println("<td>Do you want to download report </td>");
req.setAttribute("data", Rows);
pw.println("<input type=\"submit\" name =\"submit1\" value=\"Export To Excel\">");
pw.println("</form>");
} catch (SQLException e) {
pw.println(e.getNextException());
} catch (ClassNotFoundException e) {
pw.println(e.getException());
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
pw.close();
}
}
}
Any help on this is highly appreciated.
Thanks,
SR

Editing PresentationML using openxml

Hello everyone i am working on a project in which i have to export some data into a ppt using openxml on button click.Here is my code for the aspx page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DocumentFormat.OpenXml.Presentation;
using ODrawing = DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml;
using DocumentFormat.Extensions1;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
namespace TableInPPT
{
public partial class _Default1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string templateFile = Server.MapPath("~/Template/Sample.potm");
string presentationFile = Server.MapPath("~/Template/SmapleNew.pptx");
PotxToPptx(templateFile, presentationFile);
//using (PresentationDocument themeDocument = PresentationDocument.Open(templateFile, false))
using (PresentationDocument prstDoc = PresentationDocument.Open(presentationFile, true))
{
AddImage(prstDoc);
AddTable(prstDoc);
}
string itemname = "SmapleNew.pptx";
Response.Clear();
Response.ContentType = "pptx";
Response.AddHeader("Content-Disposition", "attachment; filename=" + itemname + "");
Response.BinaryWrite(System.IO.File.ReadAllBytes(presentationFile));
Response.Flush();
Response.End();
}
private void PotxToPptx(string templateFile, string presentationFile)
{
MemoryStream presentationStream = null;
using (Stream tplStream = File.Open(templateFile, FileMode.Open, FileAccess.Read))
{
presentationStream = new MemoryStream((int)tplStream.Length);
tplStream.Copy(presentationStream);
presentationStream.Position = 0L;
}
using (PresentationDocument pptPackage = PresentationDocument.Open(presentationStream, true))
{
pptPackage.ChangeDocumentType(DocumentFormat.OpenXml.PresentationDocumentType.Presentation);
PresentationPart presPart = pptPackage.PresentationPart;
presPart.PresentationPropertiesPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate",
new Uri(templateFile, UriKind.RelativeOrAbsolute));
presPart.Presentation.Save();
}
File.WriteAllBytes(presentationFile, presentationStream.ToArray());
}
private void AddTable(PresentationDocument prstDoc)
{
// Add one slide
Slide slide = prstDoc.PresentationPart.InsertSlide1("Custom Layout", 2);
Shape tableShape = slide.CommonSlideData.ShapeTree.ChildElements.OfType<Shape>()
.Where(sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Title.Value == "TableHolder").SingleOrDefault();
if (tableShape == null) return;
// Create Graphic Frame
OpenXmlCompositeElement gElement = GetGraphicFrame(tableShape);
// Create a (6x3)Table
ODrawing.Table openXmlTable = GetSmapleTable();
// add table to graphic element
gElement.GetFirstChild<ODrawing.Graphic>().GetFirstChild<ODrawing.GraphicData>().Append(openXmlTable);
slide.CommonSlideData.ShapeTree.Append(gElement);
slide.CommonSlideData.ShapeTree.RemoveChild<Shape>(tableShape);
prstDoc.PresentationPart.Presentation.Save();
}
private void AddImage(PresentationDocument prstDoc)
{
string imgpath = Server.MapPath("~/Template/xxxx.jpg");
Slide slide = prstDoc.PresentationPart.InsertSlide("Title and Content", 2);
Shape titleShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());
titleShape.NonVisualShapeProperties = new NonVisualShapeProperties
(new NonVisualDrawingProperties() { Id = 2, Name = "Title" },
new NonVisualShapeDrawingProperties(new ODrawing.ShapeLocks() { NoGrouping = true }),
new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title }));
titleShape.ShapeProperties = new ShapeProperties();
// Specify the text of the title shape.
titleShape.TextBody = new TextBody(new ODrawing.BodyProperties(),
new ODrawing.ListStyle(),
new ODrawing.Paragraph(new ODrawing.Run(new ODrawing.Text() { Text = "Trade Promotion Graph " })));
Shape shape = slide.CommonSlideData.ShapeTree.Elements<Shape>().FirstOrDefault(
sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Name.Value.ToLower().Equals("Content Placeholder 2".ToLower()));
Picture pic = slide.AddPicture(shape, imgpath);
slide.CommonSlideData.ShapeTree.RemoveChild<Shape>(shape);
slide.Save();
prstDoc.PresentationPart.Presentation.Save();
}
private ODrawing.Table GetSmapleTable()
{
ODrawing.Table table = new ODrawing.Table();
ODrawing.TableProperties tableProperties = new ODrawing.TableProperties();
ODrawing.TableStyleId tableStyleId = new ODrawing.TableStyleId();
tableStyleId.Text = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}";
//tableStyleId.Text = "{D27102A9-8310-4765-A935-A1911B00CA55}";
tableProperties.Append(tableStyleId);
ODrawing.TableGrid tableGrid = new ODrawing.TableGrid();
ODrawing.GridColumn gridColumn1 = new ODrawing.GridColumn() { Width = 2600000L};
ODrawing.GridColumn gridColumn2 = new ODrawing.GridColumn() { Width = 2600000L };
//ODrawing.GridColumn gridColumn3 = new ODrawing.GridColumn() { Width = 1071600L };
//ODrawing.GridColumn gridColumn4 = new ODrawing.GridColumn() { Width = 1571600L };
//ODrawing.GridColumn gridColumn5 = new ODrawing.GridColumn() { Width = 771600L };
//ODrawing.GridColumn gridColumn6 = new ODrawing.GridColumn() { Width = 1071600L };
tableGrid.Append(gridColumn1);
tableGrid.Append(gridColumn2);
//tableGrid.Append(gridColumn3);
//tableGrid.Append(gridColumn4);
//tableGrid.Append(gridColumn5);
//tableGrid.Append(gridColumn6);
table.Append(tableProperties);
table.Append(tableGrid);
for (int row = 1; row <= 5; row++)
{
string text1 = "PARAMETERS";
string text2="VALUES";
if (row == 2)
{
text1 =Label1.Text ;
text2 = TextBox1.Text;
}
if (row == 3)
{
text1 = Label2.Text;
text2 = TextBox2.Text;
}
if (row == 4)
{
text1 = Label3.Text;
text2 = TextBox3.Text;
}
if (row == 5)
{
text1 = Label4.Text;
text2 = TextBox4.Text;
}
ODrawing.TableRow tableRow = new ODrawing.TableRow() { Height = 370840L };
tableRow.Append(new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.RunProperties() {Language = "en-US", Dirty = false, SmartTagClean = false , FontSize = 3000},
new ODrawing.Text(text1)))),
new ODrawing.TableCellProperties()));
tableRow.Append(new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.RunProperties() {Language = "en-US", Dirty = false, SmartTagClean = false , FontSize = 3000 },
new ODrawing.Text(text2)))),
new ODrawing.TableCellProperties()));
ODrawing.SolidFill solidFill = new ODrawing.SolidFill();
ODrawing.SchemeColor schemeColor = new ODrawing.SchemeColor() { Val = ODrawing.SchemeColorValues.Accent6 };
ODrawing.LuminanceModulation luminanceModulation = new ODrawing.LuminanceModulation() { Val = 75000 };
schemeColor.Append(luminanceModulation);
solidFill.Append(schemeColor);
table.Append(tableRow);
}
//for (int row = 1; row <= 3; row++)
//{
// ODrawing.TableRow tableRow = new ODrawing.TableRow() { Height = 370840L };
// for (int column = 1; column <= 6; column++)
// {
// ODrawing.TableCell tableCell = new ODrawing.TableCell();
// TextBody textBody = new TextBody() { BodyProperties = new ODrawing.BodyProperties(), ListStyle = new ODrawing.ListStyle() };
// ODrawing.Paragraph paragraph = new ODrawing.Paragraph();
// ODrawing.Run run = new ODrawing.Run();
// ODrawing.RunProperties runProperties = new ODrawing.RunProperties() { Language = "en-US", Dirty = false, SmartTagClean = false };
// ODrawing.Text text = new ODrawing.Text();
// text.Text = "Smaple Text";
// run.Append(runProperties);
// run.Append(text);
// ODrawing.EndParagraphRunProperties endParagraphRunProperties = new ODrawing.EndParagraphRunProperties() { Language = "en-US", Dirty = false };
// paragraph.Append(run);
// paragraph.Append(endParagraphRunProperties);
// textBody.Append(paragraph);
// ODrawing.TableCellProperties tableCellProperties = new ODrawing.TableCellProperties();
// ODrawing.SolidFill solidFill = new ODrawing.SolidFill();
// ODrawing.SchemeColor schemeColor = new ODrawing.SchemeColor() { Val = ODrawing.SchemeColorValues.Accent6 };
// ODrawing.LuminanceModulation luminanceModulation = new ODrawing.LuminanceModulation() { Val = 75000 };
// schemeColor.Append(luminanceModulation);
// solidFill.Append(schemeColor);
// tableCellProperties.Append(solidFill);
// tableCell.Append(textBody);
// tableCell.Append(tableCellProperties);
// tableRow.Append(tableCell);
// if (column == 1 && row == 1)
// {
// tableRow.Append(CreateTextCell("category"));
// }
// }
// }
return table;
}
static ODrawing.TableCell CreateTextCell(string text)
{
ODrawing.TableCell tc = new ODrawing.TableCell(
new ODrawing.TextBody(
new ODrawing.BodyProperties(),
new ODrawing.Paragraph(
new ODrawing.Run(
new ODrawing.Text(text)))),
new ODrawing.TableCellProperties());
return tc;
}
private static OpenXmlCompositeElement GetGraphicFrame(Shape refShape)
{
GraphicFrame graphicFrame = new GraphicFrame();
int contentPlaceholderCount = 0;
UInt32Value graphicFrameId = 1000;
NonVisualGraphicFrameProperties nonVisualGraphicFrameProperties = new NonVisualGraphicFrameProperties();
NonVisualDrawingProperties nonVisualDrawingProperties = new NonVisualDrawingProperties()
{
Id = ++graphicFrameId,
Name = "Table" + contentPlaceholderCount.ToString(),
};
NonVisualGraphicFrameDrawingProperties nonVisualGraphicFrameDrawingProperties = new NonVisualGraphicFrameDrawingProperties();
ODrawing.GraphicFrameLocks graphicFrameLocks = new ODrawing.GraphicFrameLocks() { NoGrouping = true };
nonVisualGraphicFrameDrawingProperties.Append(graphicFrameLocks);
ApplicationNonVisualDrawingProperties applicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
PlaceholderShape placeholderShape = new PlaceholderShape() { Index = graphicFrameId };
applicationNonVisualDrawingProperties.Append(placeholderShape);
nonVisualGraphicFrameProperties.Append(nonVisualDrawingProperties);
nonVisualGraphicFrameProperties.Append(nonVisualGraphicFrameDrawingProperties);
nonVisualGraphicFrameProperties.Append(applicationNonVisualDrawingProperties);
Transform transform = new Transform()
{
Offset = new ODrawing.Offset() { X = refShape.ShapeProperties.Transform2D.Offset.X, Y = refShape.ShapeProperties.Transform2D.Offset.Y },
Extents = new ODrawing.Extents() { Cx = refShape.ShapeProperties.Transform2D.Extents.Cx, Cy = refShape.ShapeProperties.Transform2D.Extents.Cy }
};
ODrawing.Graphic graphic = new ODrawing.Graphic();
ODrawing.GraphicData graphicData = new ODrawing.GraphicData() { Uri = "http://schemas.openxmlformats.org/drawingml/2006/table" };
graphic.Append(graphicData);
graphicFrame.Append(nonVisualGraphicFrameProperties);
graphicFrame.Append(transform);
graphicFrame.Append(graphic);
return graphicFrame;
}
}
}
Please note that the template used is a sample template containing two slides only i.e. one title slide and one more blank side with a wordart having some random text written on it.
Also the table is filled with data from 4 textboxes present on the aspx page.
And here is the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
using DocumentFormat.OpenXml.Presentation;
using ODrawing = DocumentFormat.OpenXml.Drawing;
using Drawing = DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml;
namespace DocumentFormat.Extensions1
{
public static class Extensions1
{
internal static Slide InsertSlide(this PresentationPart presentationPart, string layoutName, int absolutePosition)
{
int slideInsertedPostion = 0;
UInt32 slideId = 256U;
slideId += Convert.ToUInt32(presentationPart.Presentation.SlideIdList.Count());
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
SlidePart sPart = presentationPart.AddNewPart<SlidePart>();
slide.Save(sPart);
SlideId newSlideId = presentationPart.Presentation.SlideIdList.AppendChild<SlideId>(new SlideId());
newSlideId.Id = slideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(sPart);
slideInsertedPostion = presentationPart.SlideParts.Count();
presentationPart.Presentation.Save();
var returnVal = ReorderSlides(presentationPart, slideInsertedPostion - 1, absolutePosition - 1);
return GetSlideByRelationshipId(presentationPart, newSlideId.RelationshipId);
}
public static Slide InsertSlide1(this PresentationPart presentationPart, string layoutName, int absolutePosition)
{
int slideInsertedPostion = 0;
UInt32 slideId = 256U;
slideId += Convert.ToUInt32(presentationPart.Presentation.SlideIdList.Count());
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
SlidePart sPart = presentationPart.AddNewPart<SlidePart>();
slide.Save(sPart);
SlideMasterPart smPart = presentationPart.SlideMasterParts.First();
SlideLayoutPart slPart = smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName));
//SlideLayoutPart slPart = smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName));
sPart.AddPart<SlideLayoutPart>(slPart);
sPart.Slide.CommonSlideData = (CommonSlideData)smPart.SlideLayoutParts.SingleOrDefault(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName)).SlideLayout.CommonSlideData.Clone();
SlideId newSlideId = presentationPart.Presentation.SlideIdList.AppendChild<SlideId>(new SlideId());
newSlideId.Id = slideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(sPart);
slideInsertedPostion = presentationPart.SlideParts.Count();
presentationPart.Presentation.Save();
var returnVal = ReorderSlides(presentationPart, slideInsertedPostion - 1, absolutePosition - 1);
return GetSlideByRelationshipId(presentationPart, newSlideId.RelationshipId);
}
internal static int ReorderSlides(PresentationPart presentationPart, int currentSlidePosition, int newPosition)
{
int returnValue = -1;
if (newPosition == currentSlidePosition) { return returnValue; }
int slideCount = presentationPart.SlideParts.Count();
if (slideCount == 0) { return returnValue; }
int maxPosition = slideCount - 1;
CalculatePositions(ref currentSlidePosition, ref newPosition, maxPosition);
if (newPosition != currentSlidePosition)
{
DocumentFormat.OpenXml.Presentation.Presentation presentation = presentationPart.Presentation;
SlideIdList slideIdList = presentation.SlideIdList;
SlideId sourceSlide = (SlideId)(slideIdList.ChildElements[currentSlidePosition]);
SlideId targetSlide = (SlideId)(slideIdList.ChildElements[newPosition]);
sourceSlide.Remove();
if (newPosition > currentSlidePosition)
{
slideIdList.InsertAfter(sourceSlide, targetSlide);
}
else
{
slideIdList.InsertBefore(sourceSlide, targetSlide);
}
returnValue = newPosition;
}
presentationPart.Presentation.Save();
return returnValue;
}
private static void CalculatePositions(ref int originalPosition, ref int newPosition, int maxPosition)
{
if (originalPosition < 0)
{
originalPosition = maxPosition;
}
if (newPosition < 0)
{
newPosition = maxPosition;
}
if (originalPosition > maxPosition)
{
originalPosition = maxPosition;
}
if (newPosition > maxPosition)
{
newPosition = maxPosition;
}
}
private static Slide GetSlideByRelationshipId(PresentationPart presentationPart, DocumentFormat.OpenXml.StringValue relId)
{
SlidePart slidePart = presentationPart.GetPartById(relId) as SlidePart;
if (slidePart != null)
{
return slidePart.Slide;
}
else
{
return null;
}
}
internal static Picture AddPicture(this Slide slide, Shape referingShape, string imageFile)
{
Picture picture = new Picture();
string embedId = string.Empty;
UInt32Value picId = 10001U;
string name = string.Empty;
if (slide.Elements<Picture>().Count() > 0)
{
picId = ++slide.Elements<Picture>().ToList().Last().NonVisualPictureProperties.NonVisualDrawingProperties.Id;
}
name = "image" + picId.ToString();
embedId = "rId" + (slide.Elements<Picture>().Count() + 915).ToString(); // some value
NonVisualPictureProperties nonVisualPictureProperties = new NonVisualPictureProperties()
{
NonVisualDrawingProperties = new NonVisualDrawingProperties() { Name = name, Id = picId, Title = name },
NonVisualPictureDrawingProperties = new NonVisualPictureDrawingProperties() { PictureLocks = new Drawing.PictureLocks() { NoChangeAspect = true } },
ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties() { UserDrawn = true }
};
BlipFill blipFill = new BlipFill() { Blip = new Drawing.Blip() { Embed = embedId } };
Drawing.Stretch stretch = new Drawing.Stretch() { FillRectangle = new Drawing.FillRectangle() };
blipFill.Append(stretch);
ShapeProperties shapeProperties = new ShapeProperties()
{
Transform2D = new Drawing.Transform2D()
{
Offset = new Drawing.Offset() { X = 1554691, Y = 1600200 },
Extents = new Drawing.Extents() { Cx = 6034617, Cy = 4525963 }
}
};
Drawing.PresetGeometry presetGeometry = new Drawing.PresetGeometry() { Preset = Drawing.ShapeTypeValues.Rectangle };
Drawing.AdjustValueList adjustValueList = new Drawing.AdjustValueList();
presetGeometry.Append(adjustValueList);
shapeProperties.Append(presetGeometry);
picture.Append(nonVisualPictureProperties);
picture.Append(blipFill);
picture.Append(shapeProperties);
slide.CommonSlideData.ShapeTree.Append(picture);
// Add Image part
slide.AddImagePart(embedId, imageFile);
slide.Save();
return picture;
}
private static void AddImagePart(this Slide slide, string relationshipId, string imageFile)
{
ImagePart imgPart = slide.SlidePart.AddImagePart(GetImagePartType(imageFile), relationshipId);
using (FileStream imgStream = File.Open(imageFile, FileMode.Open))
{
imgPart.FeedData(imgStream);
}
}
private static ImagePartType GetImagePartType(string imageFile)
{
string[] imgFileSplit = imageFile.Split('.');
string imgExtension = imgFileSplit.ElementAt(imgFileSplit.Count() - 1).ToString().ToLower();
if (imgExtension.Equals("jpg"))
imgExtension = "jpeg";
return (ImagePartType)Enum.Parse(typeof(ImagePartType), imgExtension, true);
}
public static void Copy(this Stream source, Stream target)
{
if (source != null)
{
MemoryStream mstream = source as MemoryStream;
if (mstream != null) mstream.WriteTo(target);
else
{
byte[] buffer = new byte[2048];
int length = buffer.Length, size;
while ((size = source.Read(buffer, 0, length)) != 0)
target.Write(buffer, 0, size);
}
}
}
}
}
Now here are my queries:
1.In the aspx page if i try to replace the templateFile with my own template(same as the sample)it gives me an error "Object reference not set to an instance of an object" at this line Where(sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Title.Value == "TableHolder") under AddTable.Otherwise it works fine.
2.Also in the second slide i am getting the required table but with the word "image" written 5 times on top of the page.
3.Also in the powerpoint file generated,the template style is not displayed on the slides except the first and the last slide(i.e the slides which are there in the template).
Thank you.

Resources