Error in saving CKEDITOR content - asp.net-mvc

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 ?

Related

uploading file using input field

I created a web app using asp.net-mvc and Jquery
when I added the below code my application automatically stop running without throwing any error, I don't know Whether it is my visual studio 19 or IIS which is being crashed
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
To verify I created an asp.net mvc sample project and paste the above code in the index page but the same problem comes
Image
what can I do to solve this?
Do you have
enctype="multipart/form-data"
property in your form element?
<form id="upload">
<input type="file" id="file" class="form-control">
</form>
Jquery
$('#upload').submit(function (e) {
e.preventDefault(); // stop the standard form submission
var File_Name = $("#file").prop('files')[0].name;
var ext = File_Name.split('.').pop();
if (ext == "pdf" || ext == "docx" || ext == "doc" || ext == "png" || ext ==
"jpg" || ext == "jpeg" || ext == "txt") {
var lastIndex = $("#file").prop('files')[0].name.lastIndexOf(".") + 1;
var form = new FormData();
form.append("file", $("#file").prop('files')[0]);
$.ajax({
url: '/Main/SaveDocument',
type: 'POST',
data: form,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data.UploadedFileCount + ' file(s) uploaded successfully');
if (data == "999") {
swal("Note", "Some Error Occurred. File Not uploaded successfully.", "error");
}
},
error: function (xhr, error, status) {
console.log(error, status + " " + xhr);
}
});
}
else {
swal("Note", "File Type Not Supported.", "warning");
}
});
C#
public ActionResult SaveDocument()
{
//file
var file = System.Web.HttpContext.Current.Request.Files["file"];
var CheckCnic = hr_FTPEntities.File_description.Where(x => x.uploader_CNIC == userCNIC).FirstOrDefault();
if(CheckCnic == null)
{
HttpPostedFileBase filebase = new HttpPostedFileWrapper(file);
if (filebase.ContentLength > 0)
{
var fileName = Path.GetFileName(filebase.FileName);
string path = Path.Combine(Server.MapPath(basePath + departmentName) + "/");
File_description file_Description = new File_description();
int fileCount = hr_FTPEntities.File_description.Select(x => x).ToList().Count + 1;
int lastIndexOfDot = fileName.LastIndexOf(".") - 1;
string finalFileName = fileName.Substring(0, lastIndexOfDot) + "_" + fileCount + fileName.Substring(lastIndexOfDot + 1);
file_Description.file_name = finalFileName.ToString();
try
{
filebase.SaveAs(path + (finalFileName));
}
catch(Exception ex)
{
return Json("999");
}
}
return Json("000");
}
else
{
return Json("888");
}
}
You could try to use the below code:
View(Index.cshtml) :
<input type="file" id="FileUpload1" />
<input type="button" id="btnUpload" value="Upload Files" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#btnUpload').click(function () {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
// Adding one more key to FormData object
fileData.append('username', 'test');
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
});
</script>
Controller (HomeController.cs):
[HttpPost]
public ActionResult UploadFiles()
{
// Checking no of files injected in Request object
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
file.SaveAs(fname);
}
// Returns message that successfully uploaded
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
Make sure your IIS site contains the upload folder and enough permission to access the folder.
If you still face the same issue then try to use the different browser.
check event viewer logs or try to collect the dup and analyze the dump using the DebugDiag tool.

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 upload File from URL

In my application am allowing the user to upload file from the URL
code to upload File URL:
function loadURL(box) {
var box = dhtmlx.modalbox({
title: "Load URL",
text: "<div id='form_in_box'><div>Enter the URL of PDF file <hr/><input type='text' name='files' id='files' style='width: 400px; height: 27px;'></label><br></div><div><span class='dhtmlx_button'><input type='submit' value='Load URL' style='width: 86px' onclick='load_file(this)'></span><span class='dhtmlx_button'><input type='button' value='Cancel' onclick='close_file(this)' style='width:80px;'></span></label></div></div>",
width: "300px"
})
}
function load_file(box) {
var file = document.getElementById('files');
if (file == "") {
alert("Enter File URL");
return false;
}
file = file.value;
var filename = file.substring(file.lastIndexOf('/') + 1);
dhtmlx.modalbox.hide(box);
$.post("/FileUpload/UploadURL",
{ file: '' + file + ''
});
}
Controller code
public ActionResult UploadURL(string file)
{
string files = Path.GetFileName(file);
string myStringWebResource = "";
WebClient myWebClient = new WebClient();
myStringWebResource = file;
string path = Server.MapPath(_fileUploadPath + files);
myWebClient.DownloadFile(myStringWebResource, path);
string extFile = Server.MapPath(_fileUploadPath + files);
return View();
}
Files are gettinig downloaded successfully. Now I want to upload the same file How can I do so?
HTML file upload control is for uploading from client's computer only. What you have to do is to download file from another server and save it at yours. This thread should help.

sending form data xmlhttprequest

In below code first am allowing the user to select the option from the drop down list and than allows to browse the file.
Code:
function choice() {
var box = dhtmlx.modalbox({
text: "<div id='form_in_box'><div>Choose a File to Convert <hr/><label>Filename: <input type='file' name='file' id='file' style='width: 400px; height: 27px;'></label><br></div><div><span class='dhtmlx_button'><input type='submit' value='Create PDF' style='width: 86px' onclick='Convert(this)'></span><span class='dhtmlx_button'><input type='button' value='Cancel' onclick='close_file(this)' style='width:80px;'></span></label></div></div>",
width: "300px"
});
}
function Convert(box) {
var ch = document.getElementById('choice');
var file = document.getElementById('file');
if (file.value == "") {
alert("Choose a file to convert");
return false;
}
dhtmlx.modalbox.hide(box);
var fd = new FormData();
fd.append('file', file.files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/FileUpload/Convert', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert('File successfully conveted to PDF');
}
};
xhr.send(fd);
}
In ch the drop down option gets saved.
I want to send ch value to the controller
Controller code:
public ActionResult Convert(HttpPostedFileBase file, FormCollection data)
{
string choice = data["choice"];
how can i send it?
You could add it to the FormData:
var fd = new FormData();
fd.append('file', file.files[0]);
fd.append('choice', ch.value);
and your controller action may now look like this:
public ActionResult Convert(HttpPostedFileBase file, string choice)
{
...
}

How to save images/shapes in PDF file

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

Resources