Writing PDF content on response stream in openrasta - pdf

I want to render a pdf in Iframe. So if I do a GET request to http://localhost/pdf/2, it should return PDF content in the response stream. The other way can be redirecting user to full URL of the PDF file which I don't want to do.
Thanks in advance

you can use the InMemoryFile and InMemoryDownloadableFile classes.
An example:
private class AttachmentFile : InMemoryDownloadableFile
{
public AttachmentFile(byte[] file, string filename, string contenttype)
{
OpenStream().Write(file, 0, file.Length);
this.FileName = filename;
this.ContentType = new MediaType(contenttype);
}
}
private class InlineFile : InMemoryFile
{
public InlineFile(byte[] file, string filename, string contenttype)
{
OpenStream().Write(file, 0, file.Length);
this.FileName = filename;
this.ContentType = new MediaType(contenttype);
}
}
[HttpOperation(HttpMethod.GET)]
public object Get(string filename)
{
bool inline = false; //server attachments inline or as download
try
{
inline = Convert.ToBoolean(Params["INLINE"]);
}
catch { }
string contenttype = set contentttype...
byte[] attachment = read file....
if (inline)
return new InlineFile(attachment, filename, contenttype);
else return new AttachmentFile(attachment, filename, contenttype);
}
else return new OperationResult.Forbidden();
}

Related

Download the file as a zip in ASP.NET Core

I am designing an educational site. When the user downloads a training course, I want this download (training course) to be done in the form of compression (zipper), please give a solution
My code:
public Tuple<byte[],string,string> DownloadFile(long episodeId)
{
var episode=_context.CourseEpisodes.Find(episodeId);
string filepath = Path.Combine(Directory.GetCurrentDirectory(),
"wwwroot/courseFiles",
episode.FileName);
string fileName = episode.FileName;
if(episode.IsFree)
{
byte[] file = System.IO.File.ReadAllBytes(filepath);
return Tuple.Create(file, "application/force-download",fileName);
}
if(_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
{
if(IsuserIncorse(_httpContextAccessor.HttpContext.User.Identity.Name,
episode.CourseId))
{
byte[] file = System.IO.File.ReadAllBytes(filepath);
return Tuple.Create(file, "application/force-download", fileName);
}
}
return null;
}
I write a demo to show how to download zip file from .net core:
First , Add NuGet package SharpZipLib , create an Image Folder in wwwroot and put some picture in it.
controller
public class HomeController : Controller
{
private IHostingEnvironment _IHosting;
public HomeController(IHostingEnvironment IHosting)
{
_IHosting = IHosting;
}
public IActionResult Index()
{
return View();
}
public FileResult DownLoadZip()
{
var webRoot = _IHosting.WebRootPath;
var fileName = "MyZip.zip";
var tempOutput = webRoot + "/Images/" + fileName;
using (ZipOutputStream IzipOutputStream = new ZipOutputStream(System.IO.File.Create(tempOutput)))
{
IzipOutputStream.SetLevel(9);
byte[] buffer = new byte[4096];
var imageList = new List<string>();
imageList.Add(webRoot + "/Images/1202.png");
imageList.Add(webRoot + "/Images/1data.png");
imageList.Add(webRoot + "/Images/aaa.png");
for (int i = 0; i < imageList.Count; i++)
{
ZipEntry entry = new ZipEntry(Path.GetFileName(imageList[i]));
entry.DateTime= DateTime.Now;
entry.IsUnicodeText = true;
IzipOutputStream.PutNextEntry(entry);
using (FileStream oFileStream = System.IO.File.OpenRead(imageList[i]))
{
int sourceBytes;
do
{
sourceBytes = oFileStream.Read(buffer, 0, buffer.Length);
IzipOutputStream.Write(buffer, 0, sourceBytes);
}while (sourceBytes > 0);
}
}
IzipOutputStream.Finish();
IzipOutputStream.Flush();
IzipOutputStream.Close();
}
byte[] finalResult = System.IO.File.ReadAllBytes(tempOutput);
if (System.IO.File.Exists(tempOutput)) {
System.IO.File.Delete(tempOutput);
}
if (finalResult == null || !finalResult.Any()) {
throw new Exception(String.Format("Nothing found"));
}
return File(finalResult, "application/zip", fileName);
}
}
when I click the downloadZip ,it will download a .zip file
The simple example that follows illustrates the use of the static ZipFile.CreateFromDirectory method which, despite the fact that it is in the System.IO.Compression namespace , actually resides in the System.IO.Compression.FileSystem assembly, so you need to add a reference to that in your controller.
[HttpPost]
public FileResult Download()
{
List<string> files = new List<string> { "filepath1", "filepath2" };
var archive = Server.MapPath("~/archive.zip");
var temp = Server.MapPath("~/temp");
// clear any existing archive
if (System.IO.File.Exists(archive))
{
System.IO.File.Delete(archive);
}
// empty the temp folder
Directory.EnumerateFiles(temp).ToList().ForEach(f => System.IO.File.Delete(f));
// copy the selected files to the temp folder
files.ForEach(f => System.IO.File.Copy(f, Path.Combine(temp, Path.GetFileName(f))));
// create a new archive
ZipFile.CreateFromDirectory(temp, archive);
return File(archive, "application/zip", "archive.zip");
}
Answer from Source - MikesDotNetting

Support to convert the HTML to PDF in Xamarin Forms

With the reference of following StackOverflow suggestion,
Convert HTML to PDF in .NET
I tried to convert the HTML file to PDF using HtmlRenderer.PdfSharp but unfortunately it shows compatible error like below,
HtmlRendererCore.PdfSharpCore 1.0.1 is not compatible with netstandard2.0 (.NETStandard,Version=v2.0). Package HtmlRendererCore.PdfSharpCore 1.0.1 supports: netcoreapp2.0 (.NETCoreApp,Version=v2.0)
HtmlRenderer.Core 1.5.0.5 is not compatible with monoandroid90 (MonoAndroid,Version=v9.0). Package HtmlRenderer.Core 1.5.0.5 supports:
- net20 (.NETFramework,Version=v2.0)
- net30 (.NETFramework,Version=v3.0)
- net35-client (.NETFramework,Version=v3.5,Profile=Client)
- net40-client (.NETFramework,Version=v4.0,Profile=Client)
- net45 (.NETFramework,Version=v4.5)
HtmlRendererCore.PdfSharpCore 1.0.1 is not compatible with monoandroid90 (MonoAndroid,Version=v9.0). Package HtmlRendererCore.PdfSharpCore 1.0.1 supports: netcoreapp2.0 (.NETCoreApp,Version=v2.0)
And I tried with wkhtmltopdf too but it throws similar error in android and other platform projects.
My requirement is to convert the HTML file to PDF file only (no need to view the PDF file, just to save it in local path).
Can anyone please provide suggestions?
Note : Need open source suggestion :)
Awaiting for your suggestions !!!
Support to convert the HTML to PDF in Xamarin Forms
You can read the HTML as a stream and store it into local like below,
public static class FileManager
{
public static async Task<MemoryStream> DownloadFileAsStreamAsync(string url)
{
try
{
var stream = new MemoryStream();
using (var httpClient = new HttpClient())
{
var downloadStream = await httpClient.GetStreamAsync(new Uri(url));
if (downloadStream != null)
{
await downloadStream.CopyToAsync(stream);
}
}
return stream;
}
catch (Exception exception)
{
return null;
}
}
public static async Task<bool> DownloadAndWriteIntoNewFile(string url, string fileName)
{
var stream = await DownloadFileAsStreamAsync(url);
if (stream == null || stream.Length == 0)
return false;
var filePath = GetFilePath(fileName);
if (!File.Exists(filePath))
return false;
File.Delete(filePath);
// Create file.
using (var createdFile = File.Create(filePath))
{
}
// Open and write into file.
using (var openFile = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite))
{
stream.WriteTo(openFile);
}
return true;
}
public static string GetFilePath(string fileName)
{
var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), fileName);
return filePath;
}
public static void WriteAsText(string filePath, string contents)
{
File.WriteAllText(filePath, contents);
}
public static string ReadAsText(string filePath)
{
return File.ReadAllText(filePath);
}
}
You can read a stored pdf file and displayed using webview like below,
private async void HtmlToPDF()
{
await FileManager.DownloadAndWriteIntoNewFile("https://www.google.co.in/?gws_rd=ssl", "SavePDF.pdf");
var filePath = FileManager.GetFilePath("SavePDF.pdf");
var pdfString = FileManager.ReadAsText(filePath);
var webView = new WebView
{
Source = new HtmlWebViewSource
{
Html = pdfString
}
};
this.Content = webView;
}
And the output below,
Likewise, you can save HTML as PDF and do what you want..
you can use the HtmlToPdfConverter
private void ConvertUrlToPdf()
{
try {
String serverIPAddress = serverIP.Text;
uint serverPortNumber = uint.Parse (serverPort.Text);
// create the HTML to PDF converter object
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter (serverIPAddress, serverPortNumber);
// set service password if necessary
if (serverPassword.Text.Length > 0)
htmlToPdfConverter.ServicePassword = serverPassword.Text;
// set PDF page size
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
// set PDF page orientation
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;
// convert the HTML page from given URL to PDF in a buffer
byte[] pdfBytes = htmlToPdfConverter.ConvertUrl (urlToConvert.Text);
string documentsFolder = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
string outPdfFile = System.IO.Path.Combine (documentsFolder, "EvoHtmlToPdf.pdf");
// write the PDF buffer in output file
System.IO.File.WriteAllBytes (outPdfFile, pdfBytes);
// open the PDF document in the default PDF viewer
UIDocumentInteractionController pdfViewer = UIDocumentInteractionController.FromUrl (Foundation.NSUrl.FromFilename (outPdfFile));
pdfViewer.PresentOpenInMenu (this.View.Frame, this.View, true);
} catch (Exception ex) {
UIAlertView alert = new UIAlertView ();
alert.Title = "Error";
alert.AddButton ("OK");
alert.Message = ex.Message;
alert.Show ();
}
}
another
you can see thisurl

"multipart config was not present on Servlet" when trying to upload a file with JAX-RS class

I have the following JAX-RS class to upload a file from a browser (implemented in Wildfly 14). Problem is I get the error multipart config was not present on Servlet. Since I annotated the class with #Consumes({ MediaType.MULTIPART_FORM_DATA }) I'm not sure what is missing. How to fix this problem?
#Produces({ MediaType.APPLICATION_JSON })
#Consumes({ MediaType.MULTIPART_FORM_DATA })
public class FileUploadService {
#Context
private HttpServletRequest request;
#POST
#Path("/upload")
public Response processUpload() throws IOException, ServletException {
String path = "/mypath";
for (Part part : request.getParts()) {
String fileName = getFileName(part);
String fullPath = path + File.separator + fileName;
// delete file if exists
java.nio.file.Path path2 = FileSystems.getDefault().getPath(fullPath);
Files.deleteIfExists(path2);
// get file input stream
InputStream fileContent = part.getInputStream();
byte[] buffer = new byte[fileContent.available()];
fileContent.read(buffer);
File targetFile = new File(fullPath);
// write output file
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
outStream.close();
}
return Response.ok("OK").build();
}
private String getFileName(Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename"))
return content.substring(content.indexOf("=") + 2, content.length() - 1);
}
return "";
}
}

ASP.NET WebApi file upload using guid and file extension

I currently am able to save a file being uploaded to a WebAPI controller, but I'd like to be able to save the file as a guid with the correct file name extension so it can be viewed correctly.
Code:
[ValidationFilter]
public HttpResponseMessage UploadFile([FromUri]string AdditionalInformation)
{
var task = this.Request.Content.ReadAsStreamAsync();
task.Wait();
using (var requestStream = task.Result)
{
try
{
// how can I get the file extension of the content and append this to the file path below?
using (var fileStream = File.Create(HttpContext.Current.Server.MapPath("~/" + Guid.NewGuid().ToString())))
{
requestStream.CopyTo(fileStream);
}
}
catch (IOException)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
}
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.Created;
return response;
}
I can't seem to get a handle on the actual filename of the content. I thought headers.ContentDisposition.FileName might be a candidate but that doesn't seem to get populated.
Thanks for the comments above which pointed me in the right direction.
To clarify the final solution, I used a MultipartFormDataStreamProvider which streams the file automatically. The code is in another question I posted to a different problem here:
MultipartFormDataStreamProvider and preserving current HttpContext
My full provider code is listed below. The key to generating the guid file name is to override the GetLocalFileName function and use the headers.ContentDisposition property. The provider handles the streaming of the content to file.
public class MyFormDataStreamProvider : MultipartFormDataStreamProvider
{
public MyFormDataStreamProvider (string path)
: base(path)
{ }
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
{
// restrict what images can be selected
var extensions = new[] { "png", "gif", "jpg" };
var filename = headers.ContentDisposition.FileName.Replace("\"", string.Empty);
if (filename.IndexOf('.') < 0)
return Stream.Null;
var extension = filename.Split('.').Last();
return extensions.Any(i => i.Equals(extension, StringComparison.InvariantCultureIgnoreCase))
? base.GetStream(parent, headers)
: Stream.Null;
}
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
// override the filename which is stored by the provider (by default is bodypart_x)
string oldfileName = headers.ContentDisposition.FileName.Replace("\"", string.Empty);
string newFileName = Guid.NewGuid().ToString() + Path.GetExtension(oldfileName);
return newFileName;
}
}

Save Image using FileSavePicker

I have an image displayed in an Image Control and I need to save that Image using FileSavePicker
This is what I have done:
Dim fileSavePicker As New FileSavePicker()
fileSavePicker.FileTypeChoices.Add("PNG", New String() {".png"})
fileSavePicker.FileTypeChoices.Add("JPG", New String() {".jpg"})
fileSavePicker.FileTypeChoices.Add("BMP", New String() {".bmp"})
fileSavePicker.FileTypeChoices.Add("TIFF", New String() {".tiff"})
fileSavePicker.FileTypeChoices.Add("EXIF", New String() {".exif"})
fileSavePicker.FileTypeChoices.Add("ICO", New String() {".ico"})
Dim saveFile As StorageFile = Await fileSavePicker.PickSaveFileAsync()
If saveFile IsNot Nothing Then
//Here I need to save that Image
End If
It is saving the image but with "0 KB" and showing me the blank Image.
What should I be doing?
Edit:
This is the error I'm getting:
SaveToFile is not a memeber of Windows.UI.XAML.Media.Imaging.WriteableBitmap'.
And similarly for 'Load'
Edit:
This is how I am trying to load image:
Private Async Sub Scenario1Button_Click(sender As Object, e As RoutedEventArgs) Handles Scenario1Button.Click
Image1.Visibility = Windows.UI.Xaml.Visibility.Visible
LayoutRoot.Visibility = Windows.UI.Xaml.Visibility.Collapsed
grdImages.Visibility = Windows.UI.Xaml.Visibility.Collapsed
Dim openPicker As New FileOpenPicker
openPicker.ViewMode = PickerViewMode.List
openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary
openPicker.FileTypeFilter.Add("*")
Dim files As IReadOnlyList(Of StorageFile) = Await openPicker.PickMultipleFilesAsync
If files.Count > 0 Then
'Application now has read/write access to the picked file(s)
For Each file In files
Dim stream = Await file.OpenAsync(Windows.Storage.FileAccessMode.Read)
Dim image As New BitmapImage()
image.SetSource(stream)
Image1.Source = image
LayoutRoot.Visibility = Windows.UI.Xaml.Visibility.Collapsed
Next file
Else
End If
End Sub
According to the documentation:
When the call to this method completes successfully, it returns a storageFile object that was created to represent the saved file. The file name, extension, and location of this storageFile match those specified by the user, but the file has no content.
To save the content of the file, your app must write the content to this storageFile.
So you get a storage file and you need to write to it.
Saving a BitmapImage is not possible, so you would need to start off by loading the image into a WriteableBitmap. If you are just copying the original file - you can just load it to a stream and save it back to the new storage file. If you want to go the WriteableBitmap route - here is a set of extension methods you could use to load/save the image if you used C#:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media.Imaging;
namespace Xyzzer.WinRT.Extensions
{
public static class WriteableBitmapSaveExtensions
{
public static async Task<WriteableBitmap> Load(string relativePath)
{
return await new WriteableBitmap(1, 1).Load(relativePath);
}
public static async Task<WriteableBitmap> Load(this WriteableBitmap writeableBitmap, string relativePath)
{
var storageFile = await Package.Current.InstalledLocation.GetFileAsync(relativePath.Replace('/', '\\'));
return await writeableBitmap.Load(storageFile);
}
public static async Task<WriteableBitmap> Load(this WriteableBitmap writeableBitmap, StorageFile storageFile)
{
var stream = await storageFile.OpenReadAsync();
var wb = new WriteableBitmap(1, 1);
wb.SetSource(stream);
return wb;
}
public static async Task SaveToFile(this WriteableBitmap writeableBitmap)
{
await writeableBitmap.SaveToFile(
KnownFolders.PicturesLibrary,
string.Format(
"{0}_{1}.png",
DateTime.Now.ToString("yyyyMMdd_HHmmss_fff"),
Guid.NewGuid()));
}
public static async Task SaveToFile(this WriteableBitmap writeableBitmap, StorageFolder storageFolder)
{
await writeableBitmap.SaveToFile(
storageFolder,
string.Format(
"{0}_{1}.png",
DateTime.Now.ToString("yyyyMMdd_HHmmss_fff"),
Guid.NewGuid()));
}
public static async Task SaveToFile(this WriteableBitmap writeableBitmap, StorageFolder storageFolder, string fileName)
{
StorageFile outputFile = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
Guid encoderId;
var ext = Path.GetExtension(fileName);
if (new[] { ".bmp", ".dib" }.Contains(ext))
{
encoderId = BitmapEncoder.BmpEncoderId;
}
else if (new[] { ".tiff", ".tif" }.Contains(ext))
{
encoderId = BitmapEncoder.TiffEncoderId;
}
else if (new[] { ".gif" }.Contains(ext))
{
encoderId = BitmapEncoder.TiffEncoderId;
}
else if (new[] { ".jpg", ".jpeg", ".jpe", ".jfif", ".jif" }.Contains(ext))
{
encoderId = BitmapEncoder.TiffEncoderId;
}
else if (new[] { ".hdp", ".jxr", ".wdp" }.Contains(ext))
{
encoderId = BitmapEncoder.JpegXREncoderId;
}
else //if (new [] {".png"}.Contains(ext))
{
encoderId = BitmapEncoder.PngEncoderId;
}
await writeableBitmap.SaveToFile(outputFile, encoderId);
}
public static async Task SaveToFile(this WriteableBitmap writeableBitmap, StorageFile outputFile, Guid encoderId)
{
try
{
Stream stream = writeableBitmap.PixelBuffer.AsStream();
byte[] pixels = new byte[(uint)stream.Length];
await stream.ReadAsync(pixels, 0, pixels.Length);
int offset;
for (int row = 0; row < (uint)writeableBitmap.PixelHeight; row++)
{
for (int col = 0; col < (uint)writeableBitmap.PixelWidth; col++)
{
offset = (row * (int)writeableBitmap.PixelWidth * 4) + (col * 4);
byte B = pixels[offset];
byte G = pixels[offset + 1];
byte R = pixels[offset + 2];
byte A = pixels[offset + 3];
// convert to RGBA format for BitmapEncoder
pixels[offset] = R; // Red
pixels[offset + 1] = G; // Green
pixels[offset + 2] = B; // Blue
pixels[offset + 3] = A; // Alpha
}
}
IRandomAccessStream writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite);
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, writeStream);
encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, 96, 96, pixels);
await encoder.FlushAsync();
await writeStream.GetOutputStreamAt(0).FlushAsync();
}
catch (Exception ex)
{
string s = ex.ToString();
}
}
}
}