I am new to this library but I couldn't find anything about downloading to the filestream with this library, I could only find a document.Save(filepath) option which is not always allowed.
I would like to create a filestream so the file gets downloaded to the directed Downloads folder.
Could someone point me in the right direct?
There is a Save overload that takes a MemoryStream object instead of path to a file.
The PDFSharp website has an example showing how to do this:
private void Page_Load(object sender, System.EventArgs e)
{
// Create new PDF document
PdfDocument document = new PdfDocument();
this.time = document.Info.CreationDate;
document.Info.Title = "PDFsharp Clock Demo";
document.Info.Author = "Stefan Lange";
document.Info.Subject = "Server time: " +
this.time.ToString("F", CultureInfo.InvariantCulture);
// Create new page
PdfPage page = document.AddPage();
page.Width = XUnit.FromMillimeter(200);
page.Height = XUnit.FromMillimeter(200);
// Create graphics object and draw clock
XGraphics gfx = XGraphics.FromPdfPage(page);
RenderClock(gfx);
// Send PDF to browser
MemoryStream stream = new MemoryStream();
document.Save(stream, false);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", stream.Length.ToString());
Response.BinaryWrite(stream.ToArray());
Response.Flush();
stream.Close();
Response.End();
}
Related
I create a simple code for generate a pdf file, this is the code
public IActionResult reporte()
{
Document doc=new Document();
MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, ms);
doc.AddAuthor("Jose");
doc.AddTitle("Example");
doc.Open();
doc.Add(new Phrase("PDF example"));
writer.Close();
doc.Close();
ms.Seek(0, SeekOrigin.Begin);
var nameFile = string.Concat("reportName", ".pdf");
return File(ms,"application/pdf",nameFile);
}
The PDF file can be opened with web explorer, it's ok but when I save the file and try to open with Adobe Acrobat Reader, show an error dialog.
I need to add some instruction for compatibility?
public MemoryStream PdfGeneration(Model model)
{
string path = HttpContext.Current.Server.MapPath("test.pdf");
path = path.Replace("\\api", "");
FileStream fs = new FileStream(path, FileMode.Create);
doc.SaveToStream(fs);
MemoryStream ms = new MemoryStream();
ms.SetLength(fs.Length);
fs.Read(ms.GetBuffer(), 0, (int)fs.Length);
ms.Flush();
fs.Close();
return ms;
}
PS: I don't want the file to be read from the disk, it has to be processed in memory.
So here I am using Spire PDF as a generator and I need to save it to memory stream and send as an attachment to mail.
To load file from stream, you can use LoadFromStream method
PdfDocument doc = new PdfDocument();
doc.LoadFromStream(Stream stream);
I am trying to create a table containing audio files, which should start playing when the user clicks the play button. This is what I've tried so far:
Controller:
[HttpGet]
public ActionResult PlayFile(string FilePath)
{
WebClient WC = new WebClient();
WC.Credentials = new System.Net.NetworkCredential("username", "password");
byte[] buff = WC.DownloadData(FilePath);
var SplitFileName = FilePath.Split('\\');
string FileName = "Recording_" + SplitFileName[SplitFileName.Count() - 1];
Response.AddHeader("Content-Disposition", "inline; filename=" + FileName);
MemoryStream stream = new MemoryStream(buff);
return new FileStreamResult(stream, "audio/wav");
//I have also tried:
//return File(buff, "audio/wav");
}
The audio tags look like this:
<td>
<audio controls preload='none'>
<source src='/Components/PlayFile?FilePath=[filename.wav]' type='audio/wav'>
</audio>
</td>
When running the site locally in Chrome, all the files have the length 0:00, and you can click the play button once but the file is not played. After the play button has been clicked once it is not possible to click it again. It is however possible to download the file
and play it. When running the site locally in Firefox, the files also have the length 0:00, and when you click the play button the control disappears. It is also possible to download the file in Firefox. Does anyone know what could be causing this?
The problem was that the audio files were in GSM format and needed to be converted to PCM. This code works:
[HttpGet]
public ActionResult PlayFile(string FilePath)
{
WebClient WC = new WebClient();
WC.Credentials = new System.Net.NetworkCredential("username", "password");
byte[] buff = WC.DownloadData(FilePath);
var SplitFileName = FilePath.Split('\\');
string FileName = "Recording_" + SplitFileName[SplitFileName.Count() - 1];
MemoryStream ms = new MemoryStream();
ms.Write(buff, 0, buff.Length);
ms.Seek(0, SeekOrigin.Begin);
MemoryStream outputStream = new MemoryStream();
using (NAudio.Wave.WaveFileReader reader = new WaveFileReader(ms))
using (NAudio.Wave.WaveStream waveStream = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(reader))
using (NAudio.Wave.WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, waveStream.WaveFormat))
{
byte[] bytes = new byte[waveStream.Length];
waveStream.Position = 0;
waveStream.Read(bytes, 0, (int)waveStream.Length);
waveFileWriter.Write(bytes, 0, bytes.Length);
waveFileWriter.Flush();
}
return File(outputStream.ToArray(), "audio/wav");
}
Can you try with below as its working for me.
public FileResult PlayFile(string FilePath)
{
return new FilePathResult(FilePath, "audio/wav");
}
Also, try changing "audio/wav" to "audio/mp3", if it helps.
The below is used to create the .xls file and download the file.
I want to download it to .xlsx file. If i simply change the extension into ".xlsx", the report directly opens in the browser. I want it to open in .xlsx extension. Kindly help me.
Below is the code reference for you,
//setting the application path to a variable
strPath = Server.MapPath("ExcelFiles");
//Creating a file name
strExportPath = "Card" + intRnd.ToString() + intRnd1.ToString() + ".xls";
hidFilePath.Value = "ExcelFiles/" + strExportPath;
//Creating the full path with the filename
strExcelPath = strPath + "\\" + strExportPath;
Session["AK_SC_CRD_EXCEL_PATH"] = strExcelPath;
StreamWriter objStreamWriter = new StreamWriter(strExcelPath, true);
//Write the XL Contents to a stream writer.
objStreamWriter.WriteLine(strXLContents);
objStreamWriter.Close();
objStreamWriter = null;
Thanks.
You may need to add a MIMETYPE for xslx to your response.
.xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Similar to below;
Response.ContentType =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Adding Following code will force your file download instead of opening in the browser.
Response.AddHeader("content-disposition", "attachment;filename=yourfilename.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
/*Add your code here to write file to response stream*/
Response.End();
Use following code to download Excel:-
HttpContext context = HttpContext.Current;
FileStream fs = null;
BinaryReader br = null;
byte[] data = null;
try
{
if (File.Exists(filePath))
{
FileInfo file = new FileInfo(filePath);
fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
br = new BinaryReader(fs, System.Text.Encoding.Default);
data = new byte[Convert.ToInt32(fs.Length)];
br.Read(data, 0, data.Length);
context.Response.Clear();
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AddHeader("content-disposition", "attachment; filename=" + file.FullName);
context.Response.AddHeader("Content-Length", file.Length.ToString());
context.Response.BinaryWrite(data);
context.Response.Flush();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
ASP.Net MVC 3
I have an Action that returns a FileStreamResult after it imports a PDF document and stamps it with a watermark. Since it is possible to have a file not found error, how do I return a view instead of a filestream?
To complicate things I am using Philip Hutchison's jQuery PDFObject (http://pdfobject.com) to call the action and render it in a DIV so I cannot redirect on the server side.
To reiterate: It's a jQuery link on the page that fills a DIV with the results from a PDF filestream. The only 'hack' thing that I can think of is to send an Error.pdf file.
Your thoughts?
I ended up creating an error PDF memory stream.
MemoryStream ms = new MemoryStream();
try
{
PdfReader reader = new PdfReader(readerURL);
StampWatermark(WO, ms, reader);
}
catch (Exception ex)
{
RenderErrorPDF(WO, ms, ex);
}
byte[] byteinfo = ms.ToArray();
ms.Write(byteinfo, 0, byteinfo.Length);
ms.Position = 0;
ms.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(ms, "application/pdf");
RenderErrorPDF method
private static void RenderErrorPDF(WorkOrder WO, MemoryStream ms, Exception ex)
{
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false);
var doc = new Document(new Rectangle(792f, 540f));
var wr = PdfWriter.GetInstance(doc, ms);
doc.Open();
doc.Add(new Paragraph("There was an error rendering the file that you requested...", new Font(bfTimes, 24f)));
doc.Add(new Paragraph(string.Format("\r\rFile: {0}", WO.DRAWING_FILE)));
doc.Add(new Paragraph(string.Format("\r\rError: {0}", ex.Message)));
wr.CloseStream = false;
doc.Close();
}