Uri is not supported when saving pdf in server folder with nreco pdf generator - asp.net-mvc

I have the following code:
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdf.PdfToolPath = "~/files/";
htmlToPdf.GeneratePdf(template);
Which throws the following error:
Uri is not supported when saving pdf in server folder with nreco pdf generator.

You will need to set a regular path to your file system like e.g. "C:\temp\myfolder\". Or use a . instead of ~ and backslashes:
htmlToPdf.PdfToolPath = ".\\files\\";
If NReco is able to deliver you an byte-array or a stream you should prefer this instead of a file and return it directly.
UPDATE:
After takeing a look into the documentation of NReco all you need to do is following:
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdf.PdfToolPath = "<CORRECT_PATH_FOR_TOOL>";
var output = htmlToPdf.GeneratePdf(template);
System.IO.File.WriteAllBytes("<OUTPUT_PATH>", output);
This should create your pdf in the OUTPUT_PATH.

#OlaFW thanx for your effort.
I got my answer.
var pdfBytes = htmlToPdf.GeneratePdf(template);
string filePath = "/files/Myfile.pdf";
string Url = System.Web.Hosting.HostingEnvironment.MapPath(filePath);
System.IO.File.WriteAllBytes(Url, pdfBytes);

Related

Remove the WebKitFormBoundary in C#

I am working on the server that receives a file stream uploaded by multipart uploader.
But I got an additional WebKitFormBoundary.
If I remove it manually, it will work. So I tried the following code:
var fileStream = File.Create(#"C:\Users\myname\Desktop\myimage.png");
stream sr = new streamReader(myStream);
string myText = sr.ReadToEnd();
string newText = myText.Substring(myText.IndexOf("‰")); // remove header
byte[] byteArray = Encoding.ASCII.GetBytes(newText);
MemoryStream data = new MemoryStream(byteArray);
data.CopyTo(filestream);
If I use the above way to convert it to string, remove boundary and convert back to stream
the first character "‰" will become "?"
(ie. So ‰PNG will become ?PNG and the file becomes not readable.)
Any suggestions?
Where could I possible got wrong?
Thanks
This drove me nuts. Finally understood that if you have access to the request, you can access just the contents (with no header) like this:
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var file = await provider.Contents[0].ReadAsStreamAsync();
Hope this helps you, or someone with the same issue.
I have got the same issue but after investigating several blogs with applied several solutions, I got final working one. Please follow below code approach to fix it.
MemoryStream memoryStream = new MemoryStream(File.ReadAllBytes(filePath));
StreamReader streamReader = new StreamReader(memoryStream, Encoding.Default, true);
memoryStream.Seek(0, SeekOrigin.Begin);
string fileString = streamReader.ReadToEnd();
string fileData = fileString.Substring(0, fileString.IndexOf("\r\n\r\n") + 4);
string finalData = Regex.Replace(fileString, fileData, "");
var fileDataArr = Regex.Split(fileData, "\r\n|\r|\n").ToList();
var resultData = Regex.Replace(finalData, fileDataArr[0] + "--", "");
byte[] buffer = Encoding.Default.GetBytes(resultData);
Steps:
Convert your filedata into memory stream which can be used to read file content.
Use StreamReader to read file content and remove webkitformBoundary Header with default Encoding format.
Code To remove first 4 lines including webkitformBoundary from Top.
Code to remove webkitformBoundary from Footer.
Convert the string into Byte Array with default encoding format to maintain the file Encoding format.
Example:
WebKitFormBoundary Header
------WebKitFormBoundaryL1NUALe5NDrNt9S0 <br/>
Content-Disposition: form-data; name="userfile"; filename="BRtestfile1.pdf" <br/>
Content-Type: application/pdf <br/>
WebKitFormBoundary Footer
------WebKitFormBoundaryL1NUALe5NDrNt9S0-- <br/>

Cache image as base64 then convert back to image

So I'm trying to cache an image if an upload fails, due to the current limitations of flutter I think I will have to save it to shared preferences as a base64 file, then get it from shared preferences, convert it back to an image then upload that to firebase storage. My current code looks like so:
void saveImageToCache(File image) async {
List<int> imageBytes = image.readAsBytesSync();
String base64Image = base64Encode(imageBytes); //convert image ready to be cached as a string
var cachedImageName = "image $fileName";
instance.setString(cachedImageName, base64Image); // set image name in shared preferences
var retrievedImage = instance.getString(cachedImageName);// once a connection has been established again, get the image file from the cache and send it to firebase storage as an image
storageReference.putData(retrievedImage, StorageMetadata(contentType: 'base64'));
var prefix = "data:image/png;base64,";
var bStr = retrievedImage.substring(prefix.length);
var bs = Base64Codec.codec.decodeString(bStr);
var file = new File("image.png");
file.writeAsBytesSync(bs.codeUnits);
uploadTask = storageReference.child(fileName).putFile(file, const StorageMetadata(contentLanguage: "en"));
}
This is failing for me at var bStr = retrievedImage.substring(prefix.length); with error type 'String' is not a subtype of type 'Uint8List' where and im still not sure if im doing the right thing.
Any help would be great thanks.
I wouldn't recommend storing binary files to shared preferences. Especially since you're building an image cache.
I'd just store them to a file.
Future<File> saveFile(File toBeSaved) async {
final filePath = '${(await getApplicationDocumentsDirectory()).path}/image_cache/image.jpg';
File(filePath)
..createSync(recursive: true)
..writeAsBytes(toBeSaved.readAsBytesSync());
}
This uses getApplicationDocumentsDirectory() from the path provider package.

How to load CSS file from profile directory (how to create URI from filepath)

My extension has saved a CSS file to the user's profile directory. Now, I want to load this CSS file into a window.
sheetsheet/utils seems to have a loadSheet(window, uri, type) method for this (https://developer.mozilla.org/en-US/Add-ons/SDK/Low-Level_APIs/stylesheet_utils) but I can't figure out how to convert my CSS file path into a URI object that is expected.
My code is something like this:
const ssutils = require("sdk/stylesheet/utils"),
windows = require("sdk/windows");
var path_to_file = "c:\users\myname\appdata\local\temp\tmppr9imy.mozrunner\myextension\mycssfile.css"
for (let wind of windows.browserWindows) {
// What is the magic function I need to use?
ssutils.loadSheet(wind, someMagicFunctionHere(path_to_file), "user");
}
The sdk/url module prvcides the function you ask.
const { fromFilename } = require("sdk/url");
...
ssutils.loadSheet(wind, fromFilename(path_to_file), "user");
fromFilename converts a path to a file: URI

C# Open Url and download a file, the last part of the file name changes

I want to download a file from an URL, the file name is updated frequently
For E.g.: filename_Date.zip where date changes.
Below is the Query I used
WebClient webClient = new WebClient();
webClient.DownloadFile("http://nppes.viva-it.com/NPPES_Deactivated_NPI_Report_081214.zip", #"C:\Users\gnanasem\Documents\NPIMatcher\NPI.zip");
Landing Page of the URL: http://nppes.viva-it.com/NPI_Files.html
Here you can see multiple files and I want to download the first one.
One way of doing this is to:
Get the HTML of the webpage
Find the URLs on the webpage using RegEx
Find the first URL containing the relevant text, in your case "Deactivated"
Download the file
I got it working like this:
using (var webClient = new WebClient())
{
var websiteHtml = webClient.DownloadString("http://nppes.viva-it.com/NPI_Files.html");
var urlPattern = "href\\s*=\\s*(?:[\"'](?<1>[^\"']*)[\"']|(?<1>\\S+))";
Match match = Regex.Match(websiteHtml, urlPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled, TimeSpan.FromSeconds(1));
var urlToDownload = string.Empty;
while (match.Success)
{
var urlFound = match.Groups[1].Value;
if (urlFound.ToLower().Contains("deactivated"))
{
urlToDownload = urlFound;
break;
}
match = match.NextMatch();
}
webClient.DownloadFile(urlToDownload, #"C:\Users\gnanasem\Documents\NPIMatcher\NPI.zip");
}

XlsSaveOptions(SaveFormat.Excel97To2003) issue in IE 8

I am generating a report in an MVC project. The user has the option of getting the report in either .pdf format or .xls
I am using Aspose.Cells for the Excel file generation. The ActionResult method below is called.
[HttpGet]
public ActionResult GenerateReport(string format, string filterDate = "")
{
//Processing occurs here to get the appropriate info from Db.
var fileFormat = format.ToUpper() == "PDF" ? Format.Pdf : Format.Csv;
var contentType = fileFormat == Format.Pdf ? "application/pdf" : "application/vnd.ms-excel";
var makePdf = fileFormat == Format.Pdf;
var fileContents = register.GetReport(makePdf, filterDate);
return File(fileContents, contentType, "Report");
}
register.GetReport() merely determines if GetExcelVersion() or GetPdfVersion() is called.
private void GetExcelVersion(MemoryStream stream, string name, string dateRequested = "")
{
var license = new Aspose.Cells.License();
license.SetLicense("Aspose.Total.lic");
var workbook = new Workbook();
var worksheet = workbook.Worksheets[0];
var cells = worksheet.Cells;
//writes out the appropriate information to the excel spreadsheet here
workbook.Save(stream, new XlsSaveOptions(Aspose.Cells.SaveFormat.Excel97To2003));
}
This works a charm in Firefox and IE10 but when testing on IE8 I receive the following alert from Excel:-
The File you are trying to open 'XXXXX', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now? Yes/No
Any ideas on what I am doing wrong?
Cheers!
As Saqib Razzaq mentioned in the comments above. Turn off compatibility mode as mentioned here

Resources