hey friends, i am using TinyMCE editor for creating the Reports, and after completion this i am sending this HTML to PDF through ITEXT, the problem is, when i am creating any table in Editor it set the width in style attribute example style="width:400px".
This width is not understandable by ITEXT it Need simple width="400", but when i am forcefully set the width in HTMl of TinyMCE, it automatically convert it into style="width:400px".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
public class GS_ImageEditing
{
#region Croping amd Resizing
private void GetCroppedCompressedImage(byte[] originalBytes, Size size, ImageFormat format, string desti)
{
using (var streamOriginal = new MemoryStream(originalBytes))
using (var imgOriginal = System.Drawing.Image.FromStream(streamOriginal))
{
//get original width and height of the incoming image
var originalWidth = imgOriginal.Width; // 1000
var originalHeight = imgOriginal.Height; // 800
//get the percentage difference in size of the dimension that will change the least
var percWidth = ((float)size.Width / (float)originalWidth); // 0.2
var percHeight = ((float)size.Height / (float)originalHeight); // 0.25
var percentage = Math.Max(percHeight, percWidth); // 0.25
//get the ideal width and height for the resize (to the next whole number)
var width = (int)Math.Max(originalWidth * percentage, size.Width); // 250
var height = (int)Math.Max(originalHeight * percentage, size.Height); // 200
//actually resize it
using (var resizedBmp = new Bitmap(width, height))
{
using (var graphics = Graphics.FromImage((System.Drawing.Image)resizedBmp))
{
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.DrawImage(imgOriginal, 0, 0, width, height);
}
//work out the coordinates of the top left pixel for cropping
var x = (width - size.Width) / 2; // 25
var y = (height - size.Height) / 2; // 0
//create the cropping rectangle
var rectangle = new Rectangle(x, y, size.Width, size.Height); // 25, 0, 200, 200
//crop
using (var croppedBmp = resizedBmp.Clone(rectangle, resizedBmp.PixelFormat))
using (var ms = new MemoryStream())
{
//get the codec needed
var imgCodec = ImageCodecInfo.GetImageEncoders().First(c => c.FormatID == format.Guid);
//make a paramater to adjust quality
var codecParams = new EncoderParameters(1);
//reduce to quality of 80 (from range of 0 (max compression) to 100 (no compression))
codecParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)16);
//save to the memorystream - convert it to an array and send it back as a byte[]
//croppedBmp.Save(HttpContext.Current.Server.MapPath("folder/1." + format.ToString()));
//croppedBmp.Save(ms, imgCodec, codecParams);
//return ms.ToArray();
croppedBmp.Save(desti);
}
}
}
}
public void FileToByteArray(string _FileName, string pDestination, Size pSize)
{
byte[] _Buffer = null;
try
{
// Open file for reading
System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open,
System.IO.FileAccess.Read);
// attach filestream to binary reader
System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
// get total byte length of the file
long _TotalBytes = new System.IO.FileInfo(_FileName).Length;
// read entire file into buffer
_Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes);
// close file reader
_FileStream.Close();
_FileStream.Dispose();
_BinaryReader.Close();
}
catch (Exception _Exception)
{
// Error
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}
GetCroppedCompressedImage(_Buffer, pSize, ImageFormat.Png, pDestination);
//return _Buffer;
}
#endregion
}
inderjeetsin...
Member
105 Points
163 Posts
how to convert style="width:400px" into simple width="400" attribute.
Aug 12, 2011 07:35 AM|LINK
hey friends, i am using TinyMCE editor for creating the Reports, and after completion this i am sending this HTML to PDF through ITEXT, the problem is, when i am creating any table in Editor it set the width in style attribute example style="width:400px". This width is not understandable by ITEXT it Need simple width="400", but when i am forcefully set the width in HTMl of TinyMCE, it automatically convert it into style="width:400px".
How Could i resolve this Problem....
Thanks and Regards
</div>Inderjeet Singh
konanki
Contributor
6198 Points
1239 Posts
Re: how to convert style="width:400px" into simple width="400" attribute.
Aug 12, 2011 10:57 AM|LINK
tinyMCE.init({
...
width : "640"
});
inderjeetsin...
Member
105 Points
163 Posts
Re: how to convert style="width:400px" into simple width="400" attribute.
Nov 28, 2012 12:04 PM|LINK
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using System.Data; public class GS_Dataset_To_JSON { public static string ConverDatasetToJson(DataSet dsDownloadJson) { StringBuilder Sb = new StringBuilder(); Sb.Append("{"); foreach (DataTable dtDownloadJson in dsDownloadJson.Tables) { string HeadStr = string.Empty; Sb.Append("\"" + dtDownloadJson.TableName + "1\": ["); for (int j = 0; j < dtDownloadJson.Rows.Count; j++) { string TempStr = HeadStr; Sb.Append("{"); for (int i = 0; i < dtDownloadJson.Columns.Count; i++) { string caption = dtDownloadJson.Columns[i].Caption; Sb.Append("\"" + caption + "\" : " + Enquote(dtDownloadJson.Rows[j][i].ToString()) + ","); } Sb.Append(TempStr + "},"); } Sb.Append("],"); } Sb.Append("}"); return Sb.ToString(); } public static string Enquote(string s) { if (s == null || s.Length == 0) { return "\"\""; } char c; int i; int len = s.Length; StringBuilder sb = new StringBuilder(len + 4); string t; sb.Append('"'); for (i = 0; i < len; i += 1) { c = s[i]; if ((c == '\\') || (c == '"') || (c == '>')) { sb.Append('\\'); sb.Append(c); } else if (c == '\b') sb.Append("\\b"); else if (c == '\t') sb.Append("\\t"); else if (c == '\n') sb.Append("\\n"); else if (c == '\f') sb.Append("\\f"); else if (c == '\r') sb.Append("\\r"); else { if (c < ' ') { //t = "000" + Integer.toHexString(c); string tmp = new string(c, 1); t = "000" + int.Parse(tmp, System.Globalization.NumberStyles.HexNumber); sb.Append("\\u" + t.Substring(t.Length - 4)); } else { sb.Append(c); } } } sb.Append('"'); return sb.ToString(); } }inderjeetsin...
Member
105 Points
163 Posts
Re: how to convert style="width:400px" into simple width="400" attribute.
Nov 28, 2012 12:05 PM|LINK
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Drawing; using System.Drawing.Imaging; using System.IO; public class GS_ImageEditing { #region Croping amd Resizing private void GetCroppedCompressedImage(byte[] originalBytes, Size size, ImageFormat format, string desti) { using (var streamOriginal = new MemoryStream(originalBytes)) using (var imgOriginal = System.Drawing.Image.FromStream(streamOriginal)) { //get original width and height of the incoming image var originalWidth = imgOriginal.Width; // 1000 var originalHeight = imgOriginal.Height; // 800 //get the percentage difference in size of the dimension that will change the least var percWidth = ((float)size.Width / (float)originalWidth); // 0.2 var percHeight = ((float)size.Height / (float)originalHeight); // 0.25 var percentage = Math.Max(percHeight, percWidth); // 0.25 //get the ideal width and height for the resize (to the next whole number) var width = (int)Math.Max(originalWidth * percentage, size.Width); // 250 var height = (int)Math.Max(originalHeight * percentage, size.Height); // 200 //actually resize it using (var resizedBmp = new Bitmap(width, height)) { using (var graphics = Graphics.FromImage((System.Drawing.Image)resizedBmp)) { graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(imgOriginal, 0, 0, width, height); } //work out the coordinates of the top left pixel for cropping var x = (width - size.Width) / 2; // 25 var y = (height - size.Height) / 2; // 0 //create the cropping rectangle var rectangle = new Rectangle(x, y, size.Width, size.Height); // 25, 0, 200, 200 //crop using (var croppedBmp = resizedBmp.Clone(rectangle, resizedBmp.PixelFormat)) using (var ms = new MemoryStream()) { //get the codec needed var imgCodec = ImageCodecInfo.GetImageEncoders().First(c => c.FormatID == format.Guid); //make a paramater to adjust quality var codecParams = new EncoderParameters(1); //reduce to quality of 80 (from range of 0 (max compression) to 100 (no compression)) codecParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)16); //save to the memorystream - convert it to an array and send it back as a byte[] //croppedBmp.Save(HttpContext.Current.Server.MapPath("folder/1." + format.ToString())); //croppedBmp.Save(ms, imgCodec, codecParams); //return ms.ToArray(); croppedBmp.Save(desti); } } } } public void FileToByteArray(string _FileName, string pDestination, Size pSize) { byte[] _Buffer = null; try { // Open file for reading System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); // attach filestream to binary reader System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream); // get total byte length of the file long _TotalBytes = new System.IO.FileInfo(_FileName).Length; // read entire file into buffer _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes); // close file reader _FileStream.Close(); _FileStream.Dispose(); _BinaryReader.Close(); } catch (Exception _Exception) { // Error Console.WriteLine("Exception caught in process: {0}", _Exception.ToString()); } GetCroppedCompressedImage(_Buffer, pSize, ImageFormat.Png, pDestination); //return _Buffer; } #endregion }inderjeetsin...
Member
105 Points
163 Posts
Re: how to convert style="width:400px" into simple width="400" attribute.
Nov 28, 2012 12:06 PM|LINK
#region Save Image string dbName = "~/HMS/GS_MyData/" + Request.Cookies["dbName"].Value; if (!Directory.Exists(MapPath(dbName + "/GS_ptRegImg"))) { Directory.CreateDirectory(MapPath(dbName + "/GS_ptRegImg")); } string sourceFile_Orig = MapPath(dbName + "/tempFolder/" + hdnfld_ImageName.Value); string destinationFile_Orig = MapPath(dbName + "/GS_ptRegImg/" + ds.Tables[0].Rows[0][0].ToString() + ".png"); GS_ImageEditing obj_ImageEditing = new GS_ImageEditing(); obj_ImageEditing.FileToByteArray(sourceFile_Orig, destinationFile_Orig, new System.Drawing.Size(215, 160)); File.Delete(sourceFile_Orig); #endregioninderjeetsin...
Member
105 Points
163 Posts
Re: how to convert style="width:400px" into simple width="400" attribute.
Apr 15, 2013 11:35 AM|LINK
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text.RegularExpressions; using System.IO; using System.Web.UI; using iTextSharp.text; using iTextSharp.text.html.simpleparser; using iTextSharp.text.pdf; using iTextSharp.text.html; using Org.BouncyCastle.Utilities; namespace GS_New_HMS.HMS.GS_PDFHelper { public class GS_pdfHelper { public string setHeader { get; set; } public string setFooter { get; set; } public string OPH { get; set; } public string LPF { get; set; } public int OPH_TopMargin { get; set; } public int LPF_BottmMargin { get; set; } GS_Helper obj_Helper = new GS_Helper(); public void ConvertHTMLToPDF(string HTMLCode, int leftMargin, int rightMargin, int topMargin, int bottomMargin, Rectangle rect) { HttpContext context = HttpContext.Current; System.IO.StringWriter stringWrite = new StringWriter(); System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWrite); /********************************************************************************/ //Try adding source strings for each image in content //string tempPostContent = obj_Helper.getImage(Regex.Replace(HTMLCode, @"^((\ \s*)+)$", "<p><br /></p>")); This regex will match the content, but not working with tags string tempPostContent = obj_Helper.getImage(Regex.Replace(HTMLCode, @"(?<=<.*?>)( \s*)+(?=</.*?>)", "<br />")); /*********************************************************************************/ //Create PDF document Document doc = new Document(rect, leftMargin, rightMargin, topMargin, bottomMargin); HTMLWorker parser = new HTMLWorker(doc); #region TODO: Implement Style Sheet //StyleSheet thStyle = new StyleSheet(); //thStyle.LoadTagStyle(HtmlTags.SPAN, HtmlTags.BACKGROUNDCOLOR, "#000000"); //List<IElement> objects = HTMLWorker.ParseToList(new StringReader(reader.ToString()), thStyle); //var output = new FileStream( HttpContext.Current.Server.MapPath("/App_Data/HTMLToPDF.pdf"), FileMode.Create); #endregion PdfWriter writer = PdfWriter.GetInstance(doc, HttpContext.Current.Response.OutputStream); doc.Open(); #region Footer Object Intialization Footer objFooter = new Footer(); objFooter.myHeader = obj_Helper.getImage(setHeader); objFooter.myFooter = obj_Helper.getImage(setFooter); objFooter.OPH = obj_Helper.getImage(OPH); objFooter.OPH_BootomMargin = bottomMargin; objFooter.OPH_LeftMargin = leftMargin; objFooter.OPH_RightMargin = rightMargin; objFooter.OPH_TopMargin = OPH_TopMargin; writer.PageEvent = objFooter; #endregion try { /* iterate over all elements */ List<IElement> objects = HTMLWorker.ParseToList( new StringReader(tempPostContent), null ); foreach (IElement element in objects) { if (element is PdfPTable) { ((PdfPTable)element).SplitLate = false; } else if (element.Chunks.Count > 0 && element.Chunks[0].Content == "breakhere") { doc.NewPage(); continue; } doc.Add(element); } } catch (Exception ex) { //Display parser errors in PDF. Paragraph paragraph = new Paragraph("Error!" + ex.Message); Chunk text = paragraph.Chunks[0] as Chunk; if (text != null) { text.Font.Color = BaseColor.RED; } doc.Add(paragraph); } finally { if (LPF.Trim() != "") { PdfPTable tbl = obj_Helper.getTable(obj_Helper.getImage(LPF), doc); float a = tbl.TotalHeight; tbl.WriteSelectedRows(0, -1, 10, tbl.TotalHeight + bottomMargin - 10, writer.DirectContent); } doc.Close(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); } } } public partial class Footer : PdfPageEventHelper { public string myHeader { get; set; } public string myFooter { get; set; } public string OPH { get; set; } public int OPH_TopMargin { get; set; } public int OPH_BootomMargin { get; set; } // That will Remain Same.. public int OPH_LeftMargin { get; set; } // That will Remain Same.. public int OPH_RightMargin { get; set; } // That will Remain Same.. GS_Helper obj_Helper = new GS_Helper(); public override void OnEndPage(PdfWriter writer, Document doc) { int pageN = writer.PageNumber; #region Bottom Page No var bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); var cb = writer.DirectContent; String text = "Page " + pageN ; iTextSharp.text.Rectangle pageSize = doc.PageSize; cb.SetRGBColorFill(100, 100, 100); cb.BeginText(); cb.SetFontAndSize(bf, 4); cb.SetTextMatrix(pageSize.GetLeft(30), pageSize.GetBottom(5)); cb.ShowText(text); cb.EndText(); cb.BeginText(); cb.SetFontAndSize(bf, 4); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Printed On " + DateTime.Now.ToShortDateString(), pageSize.GetRight(30), pageSize.GetBottom(5), 0); cb.EndText(); cb.SetRGBColorFill(0, 0, 0); #endregion //Paragraph footer = new Paragraph(); string header = myHeader; string footer = myFooter; if (OPH.Trim() != "") { if (pageN > 1) { header = OPH; doc.SetMargins(OPH_LeftMargin, OPH_RightMargin, OPH_TopMargin - 15, OPH_BootomMargin); // Maintain the Header Footer Space.. } } GS_SetHeaderFooter(header, doc, writer, true); GS_SetHeaderFooter(footer, doc, writer, false); } private void GS_SetHeaderFooter(string html, Document doc, PdfWriter writer, bool isHeader) { PdfPTable tbl = obj_Helper.getTable(html, doc); if (isHeader) tbl.WriteSelectedRows(0, -1, doc.LeftMargin, doc.PageSize.Height, writer.DirectContent); else tbl.WriteSelectedRows(0, -1, doc.LeftMargin, tbl.TotalHeight, writer.DirectContent); } } class GS_Helper { public string getImage(string input) { if (input == null) return string.Empty; string tempInput = input; string pattern = @"<img(.|\n)+?>"; string src = string.Empty; HttpContext context = HttpContext.Current; //Change the relative URL's to absolute URL's for an image, if any in the HTML code. foreach (Match m in Regex.Matches(input, pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.RightToLeft)) { if (m.Success) { string tempM = m.Value; string pattern1 = "src=[\'|\"](.+?)[\'|\"]"; Regex reImg = new Regex(pattern1, RegexOptions.IgnoreCase | RegexOptions.Multiline); Match mImg = reImg.Match(m.Value); if (mImg.Success) { src = mImg.Value.Replace("src=", "").Replace("\"", ""); if (src.ToLower().Contains("http://") == false) { //Insert new URL in img tag src = "src=\"" + context.Request.Url.Scheme + "://" + context.Request.Url.Authority + src + "\""; try { tempM = tempM.Remove(mImg.Index, mImg.Length); tempM = tempM.Insert(mImg.Index, src); //insert new url img tag in whole html code tempInput = tempInput.Remove(m.Index, m.Length); tempInput = tempInput.Insert(m.Index, tempM); } catch (Exception e) { } } } } } return tempInput; } public string getSrc(string input) { string pattern = "src=[\'|\"](.+?)[\'|\"]"; System.Text.RegularExpressions.Regex reImg = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Multiline); System.Text.RegularExpressions.Match mImg = reImg.Match(input); if (mImg.Success) { return mImg.Value.Replace("src=", "").Replace("\"", ""); ; } return string.Empty; } public PdfPTable getTable(string html, Document doc) { List<IElement> ie = HTMLWorker.ParseToList( new StringReader(html), null ); PdfPTable tbl = new PdfPTable(1); tbl.TotalWidth = doc.PageSize.Width - doc.LeftMargin - doc.RightMargin; //this centers [table] foreach (IElement element in ie) { PdfPTable table = element as PdfPTable; PdfPCell cell = new PdfPCell(); //cell.MinimumHeight = 101.0F; cell.AddElement(table); cell.BorderWidth = 0; tbl.AddCell(cell); } return tbl; } } /* * add a class that inherits from PdfPageEventHelper */ public class Watermark { private int _pageNo = 0; private Font _font; private iTextSharp.text.Image _image; private PdfGState _state; public Watermark() { _font = new Font( Font.FontFamily.HELVETICA, 40, Font.BOLD, new GrayColor(0.75f) ); _image = iTextSharp.text.Image.GetInstance("http://goo.gl/uWeh5"); _image.SetAbsolutePosition(200, 400); // set transparency, see commented section below; 'image watermark' _state = new PdfGState() { FillOpacity = 0.3F, StrokeOpacity = 0.3F }; } } } string HTMLCode = string.Empty; HTMLCode = hdnfld_Page.Value; string pattern = @"\w+\:\/\/[^\/]+\/"; HTMLCode = Regex.Replace(hdnfld_Page.Value, pattern, "/");