How to save images/shapes in PDF file - asp.net-mvc

In my application am allowing the user to create PDF file. Also the user can add shapes(like rectangle, line),, form fields (textarea, checkbox..) in the PDF file. when user clicks on save button PDF gets created successfully but the shapes and form fields that user has included in his document doesn't appear.
function create_PDF(box) {
var filename = $("#filename").val();
if (filename == "") {
alert("Enter filename");
return false;
}
var content = CKEDITOR.instances["message"].getData();
if (content == "") {
alert("Enter Content in The Editor");
return false;
}
content = content.trim();
dhtmlx.modalbox.hide(box);
dhtmlx.message("Saving file...");
$.post("/FileUpload/CreateNewPDFile",
{
filename: '' + filename + '', content: '' + content + ''
}, function (data) {
alert("PDF File created succesfully");
CKEDITOR.instances["message"].setData("");
CKEDITOR.instances["editor1"].setData("");
});
}
[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult CreateNewPDFile(FormCollection data)
{
var filename = data["filename"];
var htmlContent = data["content"];
string sFilePath = Server.MapPath(_createdPDF + filename + ".pdf");
htmlContent = htmlContent.Trim();
htmlContent = htmlContent.Replace("<p>", "\n").Replace("</p>", "\n");
Regex reg = new Regex("<[^>]+>", RegexOptions.IgnoreCase);
if (!System.IO.File.Exists(sFilePath))
{
Document doc = new Document(PageSize.A4, 10, 10, 10, 10);
doc.SetMargins(50, 50, 50, 50);
doc.SetPageSize(new iTextSharp.text.Rectangle(iTextSharp.text.PageSize.LETTER.Width, iTextSharp.text.PageSize.LETTER.Height));
PdfWriter.GetInstance(doc, new System.IO.FileStream(sFilePath, System.IO.FileMode.Create));
iTextSharp.text.Font fnt = FontFactory.GetFont("Times New Roman", 14);
doc.Open();
PdfPTable pdfTab = new PdfPTable(1);
PdfPCell pdfCell = null;
pdfCell = new PdfPCell(new Phrase(new Chunk(htmlContent)));
pdfTab.AddCell(pdfCell);
doc.Add(pdfTab);
doc.Close();
Response.ContentType = "application/pdf";
System.Web.HttpContext.Current.Response.Write(doc);
Response.Flush();
Response.End();
}
return View();
}
If use includes textarea , rectangle and checkmark in the newly created PDF instead of textarea, rectangle and checkmark the following thing appears how can i avoid this code and can display on the respective images in the document

Related

Summernote image upload with .NET Core

Im really struggling to get SummerNote to upload an iamge in .NET core. The trouble is the IFormFile file parameter is null when a new image is uploaded.
I initialise Summernote using the following -
$('#MessageBody').summernote({
height: ($(window).height() - 300),
callbacks: {
onImageUpload: function(image) {
uploadImage(image[0]);
}
}
});
Here is the uploadImage function -
function uploadImage(image) {
var data = new FormData();
data.append("image", image);
$.ajax({
url: '/EmailTemplate/UploadImage',
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function(url) {
var image = $('<img>').attr('src', 'http://' + url);
$('#MessageBody').summernote("insertNode", image[0]);
alert(url);
var imgNode = document.createElement('img');
imgNode.src = url;
$('#MessageBody').summernote('insertNode', imgNode);
},
error: function(data) {
console.log(data);
}
});
And finally, here is the controller -
[HttpPost]
public async Task<IActionResult> UploadImage(IFormFile file)
{
string message;
var saveimg = Path.Combine(_hostingEnvironment.WebRootPath, "Images", file.FileName);
string imgext = Path.GetExtension(file.FileName);
if (imgext == ".jpg" || imgext == ".png")
{
using (var uploadimg = new FileStream(saveimg, FileMode.Create))
{
await file.CopyToAsync(uploadimg);
message = "The selected file" + file.FileName + " is saved";
}
}
else
{
message = "only JPG and PNG extensions are supported";
}
// return "filename : " + saveimg + " message :" + message;
return Content(Url.Content(saveimg));
}
The parameter is called file while the field name is image. To fix this use the same name, either file or image.
The IFormFile type represents the value of an input type=file field. IFormFile parameters are bound to fields based on their name. There may be many file fields in the same form so the type isn't enough to determine the field.
Field binding is explained in the Sources section of the Model Binding document.

Mail pdf Attachment using Rotativa

Sending the email and the attachment actaly works. my issue is i get this error when trying to send the "generated pdf"
An exception of type 'System.Exception' occurred in Rotativa.dll but was not handled in user code
Additional information: Error: Failed loading page http://localhost:49224/Offer/OfferPdf/4 (sometimes it will work just to ignore this error with --load-error-handling ignore)
The mail test in the controller:
public ActionResult MailTest()
{
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress(CoEmail));
msg.From = new MailAddress(MailFrom, UserName);
msg.Subject = "Offer";
msg.Body = "This is a Test";
MemoryStream stream = new MemoryStream(OffersPdfMail (4, "Offer"));
Attachment att1 = new Attachment(stream, "Offer.pdf", "application/pdf");
msg.Attachments.Add(att1);
msg.IsBodyHtml = true;
msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.SubjectEncoding = System.Text.Encoding.Default;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(User, Pass);
client.Port = 587; //
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
try
{
client.Send(msg);
return RedirectToAction("index");
}
catch (Exception ex)
{
return HttpNotFound();
}
}
The Byte[]:
public Byte[] OfferPdfMail(int? id, string filename)
{
var mailpdft = new ActionAsPdf("OfferPdf/4")
{
FileName = "Offer",
PageSize = Rotativa.Options.Size.A4,
PageWidth = 210,
PageHeight = 297
};
Byte[] PdfData = mailpdft.BuildPdf(ControllerContext);
return PdfData;
and last the ViewasPdf:
public ActionResult OfferPdf (int? id, string filename)
{
string footer = "test" ;
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var pdf = new ViewAsPdf("TilbudsPdf") {
FileName = filename,
PageSize = Rotativa.Options.Size.A4,
PageOrientation = Rotativa.Options.Orientation.Portrait,
PageMargins = new Rotativa.Options.Margins(12, 12, 12, 12),// it’s in millimeters
PageWidth = 210,
PageHeight = 297,
CustomSwitches = footer };
return pdf;
}
Editted the names to english. may have missed some.
Thanks for your patience, and sorry for the bad english.
Best regards Eric
I found an solution, it was because i was stupid trying to making an pdf of a pdf. so i made a new ActionResult method like this:
public ActionResult tilbudspdfMailView(int? id, string filename)
{
Offer Offer= db.Offer.Find(id);
return View("OfferPdf", Offer);
}

How to export to pdf, word, excel file

I use ASP.net MVC 3.
I have these two requirement.
Frist one is creating invoice in my application. I want to export the datas to pdf , word , excel file. I downloaded itextsharp dll, can anyone tel me is there anyother alternative to datas in the ui to pdf, word and excel document?
Second is I need print the document after clicking the print button. How to connect printer with the print button in the exported document ?
You can use a snippet.
This one is great. Take a look on it.
This is an example of usage:
HTML
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" AllowPaging ="true"
OnPageIndexChanging = "OnPaging" >
<Columns>
<asp:BoundField ItemStyle-Width = "150px" DataField = "CustomerID"
HeaderText = "CustomerID" />
<asp:BoundField ItemStyle-Width = "150px" DataField = "City"
HeaderText = "City"/>
<asp:BoundField ItemStyle-Width = "150px" DataField = "Country"
HeaderText = "Country"/>
<asp:BoundField ItemStyle-Width = "150px" DataField = "PostalCode"
HeaderText = "PostalCode"/>
</Columns>
</asp:GridView>
C# for pdf example
protected void btnExportPDF_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
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();
}
C# for excel example
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Apply style to Individual Cells
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");
for (int i = 0; i < GridView1.Rows.Count;i++ )
{
GridViewRow row = GridView1.Rows[i];
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
row.Attributes.Add("class", "textmode");
//Apply style to Individual Cells of Alternating Row
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
row.Cells[3].Style.Add("background-color", "#C2D69B");
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}

Error in saving CKEDITOR content

In my application am allowing the user to create PDF file. Have used CKEDITOR in my application.
function create_PDF(box) {
var filename = $("#filename").val();
if (filename == "") {
alert("Enter filename");
return false;
}
var content = CKEDITOR.instances["message"].getData();
if (content == "") {
alert("Enter Content in The Editor");
return false;
}
content = content.trim();
dhtmlx.modalbox.hide(box);
dhtmlx.message("Saving file...");
$.post("/FileUpload/CreateNewPDFile",
{
filename: '' + filename + '', content: '' + content + ''
}, function (data) {
alert("PDF File created succesfully");
CKEDITOR.instances["message"].setData("");
});
}
CreateNewPDFFile controller code is:
public ActionResult CreateNewPDFile(FormCollection data)
{
var filename = data["filename"];
var htmlContent = data["content"];
string sFilePath = Server.MapPath(_createdPDF + filename + ".pdf");
htmlContent = htmlContent.Trim();
if (!System.IO.File.Exists(sFilePath))
{
Document doc = new Document(PageSize.A4, 10, 10, 10, 10);
doc.SetMargins(50, 50, 50, 50);
doc.SetPageSize(new iTextSharp.text.Rectangle(iTextSharp.text.PageSize.LETTER.Width, iTextSharp.text.PageSize.LETTER.Height));
PdfWriter.GetInstance(doc, new System.IO.FileStream(sFilePath, System.IO.FileMode.Create));
iTextSharp.text.Font fnt = FontFactory.GetFont("Times New Roman", 14);
doc.Open();
PdfPTable pdfTab = new PdfPTable(1);
PdfPCell pdfCell = null;
pdfCell = new PdfPCell(new Phrase(new Chunk(htmlContent)));
pdfTab.AddCell(pdfCell);
doc.Add(pdfTab);
doc.Close();
Response.ContentType = "application/pdf";
System.Web.HttpContext.Current.Response.Write(doc);
Response.Flush();
Response.End();
}
return View();
}
PDF file gets created successfully but the displays HTML content in it
for example: If i have inserted radio buttons in the file than in newly created file it displays
<input name="age" type="radio"
value="15-20" />
and not the radio buttons.
How can I avoid html content ?

Downloading File in ASP mvc .net

I Put The Download Link in jqgrid, my Files are Stored on server not in database, files are of different types(extension)
i want user should download file when he clicks on download link
Code For Loading jqgrid is as Follws
public object GetJSONFormatProjectDetails(List<ProjectMasterDTO> listProjectDTO, int SkipCount)
{
var data = (listProjectDTO.Select(c => new
{
id = c.ProjectID,
cell = new[]
{
c.ProjectName,
c.OfficeName,
c.ProjectType,
c.ProjectNature,
c.EntrepreneurName,
c.Year + " Years " +c.Month + " Months " + c.Day + " Days" ,
c.ConcessionWEFdate,
c.ProjectStartDate,
c.ProjectEndDate,
c.isRoadApplicable,
(c.FilePath != "NA" ) ? "<a href='#' style='color:green' onclick='DownLoadFile(\""+URLEncrypt.EncryptParameters(new string[]{ "filepath =" +c.FilePath.Replace("/","$").Replace(" ","#").Trim()})+"\");return false;'>"+(c.FilePath != "NA" ? "DownLoad":"Not Available") + " </a>" : "<span style='color:Red' >Not Available</span>"
}
})).ToArray().Skip(SkipCount);
return data;
}
JS File Code is As Follows
function DownLoadFile(param) {
$.ajax({
url: "/Home/GetFile?parameter=" + param,
cache: false,
type: "POST",
async: false
});
}
Code in Controller as follows
public ActionResult GetFile(string parameter)
{
string queryStringParameters = Request.QueryString["parameter"];
if (queryStringParameters == null)
{
throw new Exception("Url is tampered");
}
string[] parameterArray = queryStringParameters.Split('/');
string param = null;
string hash = null;
string key = null;
if (parameterArray.Length == 3)
{
param = parameterArray[0];
hash = parameterArray[1];
key = parameterArray[2];
}
if (!(string.IsNullOrEmpty(parameter)))
{
Dictionary<string, string> parameters = URLEncrypt.DecryptParameters(new string[] { param, hash, key });
string FilePath =string.Empty ;
parameters.TryGetValue("filepath", out FilePath);
FilePath = FilePath.Replace('$','\\');
// DownloadFile(FilePath);
string name = Path.GetFileName(FilePath);
string ext = Path.GetExtension(FilePath);
string type = "";
// set known types based on file extension
if (ext != null)
{
switch (ext.ToLower())
{
case ".pdf":
type = "Application/pdf";
break;
case ".doc":
case ".docx":
type = "Application/msword";
break;
case ".jpg":
case ".bmp":
case ".tiff":
case ".png":
case ".gif":
case ".jpeg":
type = "Application/Image";
break;
default:
type = "Application";
break;
}
}
Response.AppendHeader("content-disposition", "attachment; filename=" + name);
if (type != "")
{
Response.ContentType = type;
}
String FullFilePath = #"F:\MHTOLL\ContractUploadDetails\" + name;
//return File(new FileStream(path + fileName, FileMode.Open), "text/plain", fileName);
// return File(new FileStream(FullFilePath, FileMode.Open), type, name);
return File(FullFilePath, type,name);
}
return null;
}
Dont mind now about return null and exception handling
also suggest for displaying .gif animation for downloading file.
I don't think you can use an AJAX call to download a file.
I think this answer will get you what you want. Be sure to read the comments about the download prompt and MIME types. Download File Using Javascript/jQuery
I recently encountered the same issue and realized that AJAX will not work to download a file. Try an ActionLink instead:
#Html.ActionLink("ButtonName", "controllerFunctionName", "controllerName", new { functionParamName = paramValue })
And you would include your function in the controller:
public ActionResult controllerFunctionName(type functionParamName){
// do your download here
}

Resources