Using FileStreamResult to display PDF in browser - filestreamresult

I am trying to display a PDF file in a browser using the action below.
When this is executed the result is an entire screen that looks like the image attached. Rendered result
It looks like MediaTypeNames.Application.Pdf is being ignored.
The same result with Chrome or Firfox.
What I am missing?
[HttpGet]
public FileResult ViewFile()
{
Response.AppendHeader("Content-Disposition", "inline; filename=" + Server.UrlEncode("file.pdf") + ";");
var path = #"C:\temp\file.pdf";
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
return new FileStreamResult(stream, MediaTypeNames.Application.Pdf);
}

You can use below below code snippet to display a PDF document in browser.
FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
fileStream.Position = 0;
return new FileStreamResult(fileStream, System.Net.Mime.MediaTypeNames.Application.Pdf);

Related

How can get byte of pdf before download? - Grails

I can download pdf file from AWS, download is working fine but I need get byte before download.
String awsBucket = params.awsBucket
String awsKey = params.awsKey
String fileName = params.fileName
String pdfLink = params.pdfLink
File file = grailsApplication.mainContext.getResource('WSCredential.properties').file
FileInputStream fileInputStream = new FileInputStream(file)
AmazonS3 s3Client = new AmazonS3Client(new PropertiesCredentials(fileInputStream))
GetObjectRequest getObjectRequest = new GetObjectRequest(awsBucket, awsKey)
userReceipt = s3Client.getObject(getObjectRequest)
if (userReceipt)
{
response.setContentType("application/image/png")
response.setHeader("Content-disposition", "attachment;filename=\"${fileName}\"")
response.outputStream << userReceipt.getObjectContent()
}
If you mean the size of PDF, then you can use HeadObject.

Aspose.Barcode cannot read DecodeType.Code128 barcode

The aspose.barcode reader is unable to read the barcode of type DecodeType.Code128
Workflow Steps
1>Using Aspose.Barcode we have created a barcode using DecodeType.Code128 and put on PDF page ( our clients use this page as separator sheet)
2>Our client then insert this barcode page between several physical documents and scanned them all, which creates big single PDF
3>Our splitting process then, loop through all pages and check if any page is barcode page, and splits the big PDF into individual small PDF
Issue is some times the scanned quality of the barcode is not that great, and in such case ASPOSE.Barcode unable to read the barcode.
I have attached couple of barcode PDF with low scanned quality, and aspose is not able to read these barcodes. I have tried different combinations of RecognitionMode and ManualHints options without any luck
Below is my code to identity barcode page
using (var fs = new FileStream(file, FileMode.Open))
{
var pdfDocument = new Document(fs);
foreach (Page page in pdfDocument.Pages)
{
var isSeparator = splitter.IsSeparator(page);
Assert.IsTrue(isSeparator);
}
}
public bool IsSeparator(Page page)
{
if (page.Resources.Images != null && page.Resources.Images.Count >= 1)
{
var img = page.Resources.Images[1];
using (MemoryStream barcodeImage = new MemoryStream())
{
img.Save(barcodeImage, ImageFormat.Jpeg);
barcodeImage.Seek(0L, SeekOrigin.Begin);
using (BarCodeReader barcodeReader = new BarCodeReader(barcodeImage, _barcodeDecodeType))
{
barcodeReader.RecognitionMode = RecognitionMode.MaxQuality;
while (barcodeReader.Read())
{
var barcodeText = barcodeReader.GetCodeText();
if (barcodeText.ToLower() == "eof")
{
return true;
}
}
}
}
}
return false;
}
Unable to reproduce the issue at my end. I used the following sample code snippet to recognize the barcode along with latest version of the API. It is always recommended to use the latest version of the API as it contains new features and improvements.
CODE:
Aspose.Pdf.License licensePdf = new Aspose.Pdf.License();
licensePdf.SetLicense(#"Aspose.Total.lic");
// bind the pdf document
Aspose.Pdf.Facades.PdfExtractor pdfExtractor = new Aspose.Pdf.Facades.PdfExtractor();
pdfExtractor.BindPdf(#"173483_2.pdf");
// extract the images
pdfExtractor.ExtractImage();
// save images to stream in a loop
while (pdfExtractor.HasNextImage())
{
// save image to stream
System.IO.MemoryStream imageStream = new System.IO.MemoryStream();
pdfExtractor.GetNextImage(imageStream);
imageStream.Position = 0;
Aspose.BarCode.BarCodeRecognition.BarCodeReader barcodeReader =
new Aspose.BarCode.BarCodeRecognition.BarCodeReader(imageStream);
while (barcodeReader.Read())
{
Console.WriteLine("Codetext found: " + barcodeReader.GetCodeText() + ", Symbology: " + barcodeReader.GetCodeType().ToString());
}
// close the reader
barcodeReader.Close();
}
Further to update you that the same query has been post on Aspose.BarCode support forum. You may please visit the link for details.
I work as developer evangelist at Aspose.

Editing docx with openxml returns invalid memorystream

I created a DLL that takes a Word template, I have code that edits the document using openXML then the result is sent via memory stream to a web service where the documents is downloaded to the user. The issue is that the memory stream is sending is either the original template document without the updates OR sends the updated Word document XML format where the document is obviously corrupted. Here is the code:
string strTemplate = AppDomain.CurrentDomain.BaseDirectory + "Report Template.docx";
WordprocessingDocument wdDocument;
//stream the template
byte[] fileBytes = File.ReadAllBytes(strTemplate);
MemoryStream memstreamDocument = new MemoryStream();
memstreamDocument.Write(fileBytes, 0, (int)fileBytes.Length);
wdDocument = WordprocessingDocument.Open(memstreamDocument, true);
//CODE TO UPDATE TEMPLATE
//Save entire document
wdDocument.MainDocumentPart.Document.Save();
After saving the document, if using the following code the memory stream returns the original template without any updates to the document:
return memstreamDocument;
If using the following code the memory stream returns the openXML data with the updates but the document is corrupted:
MemoryStream memstreamUpdatedDocument = new MemoryStream();
Stream streamDocument = wdDocument.MainDocumentPart.GetStream();
streamDocument.CopyTo(memstreamUpdatedDocument);
return memstreamUpdatedDocument;
Here is my code in the web service which works fine:
HttpResponse response = HttpContext.Current.Response;
MemoryStream stream = GR.GetReport("", intReportID, Culture, ConnectionString, false);
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.AddHeader("content-disposition", "attachment; filename=\"" + "Report_" + intReportID+ ".docx\"");
response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
stream.Position = 0;
stream.CopyTo(response.OutputStream);
response.End();
return response;
After reviewing the supplied code I have provided a modified code snippet that should fit your needs of returning a modified MemoryStream from a file template using the WordprocessingDocument class by OpenXML. Your web service code snippet provided should work as is.
// file path of template
string strTemplate = AppDomain.CurrentDomain.BaseDirectory + "Report Template.docx";
// create FileStream to read from template
FileStream fsTemplate = new FileStream(strTemplate, FileMode.Open, FileAccess.Read);
// create MemoryStream to copy template into and modify as needed
MemoryStream msDocument = new MemoryStream();
// copy template FileStream into document MemoryStream
fsTemplate.CopyTo(msDocument);
// close the template FileStream as it is no longer necessary
fsTemplate.Close();
// reset cursor position of document MemoryStream back to top
// before modifying
msDocument.Position = 0;
// create WordProcessingDocument using the document MemoryStream
using (WordprocessingDocument wdDocument = WordprocessingDocument.Open(msDocument, true)) {
//Access the main Workbook part, which contains all references.
MainDocumentPart mainPart = wdDocument.MainDocumentPart;
/* ... CODE TO UPDATE TEMPLATE ... */
// save modification to main document part
wdDocument.MainDocumentPart.Document.Save();
// close wdDocument as it is no longer needed
wdDocument.Close();
}
// reset cursor position of document MemoryStream back to top
msDocument.Position = 0;
// return memory stream as promised
return msDocument;

How to create PPTX file using power-point-template using Apache POI

I want to create power-point presentation using power-point-template(which may be already exists or may be generated by poi.) for creating power point template file which have a background image in the slides, I write the following code which creates template file which opens in open-office but giving error to opening in Microsoft-power-point.
The Code is
private static void generatePOTX() throws IOException, FileNotFoundException {
String imgPathStr = System.getProperty("user.dir") + "/src/resources/images/TestSameChnl_001_t.jpeg";
File imgFile = new File(imgPathStr);
File potxFile = new File(System.getProperty("user.dir") + "/src/resources/Examples/layout.potx");
FileOutputStream out = new FileOutputStream(potxFile);
HSLFSlideShow ppt = new HSLFSlideShow();
HSLFSlide slide = ppt.createSlide();
slide.setFollowMasterBackground(false);
HSLFFill fill = slide.getBackground().getFill();
HSLFPictureData pd = ppt.addPicture(imgFile, PictureData.PictureType.JPEG);
fill.setFillType(HSLFFill.FILL_PICTURE);
fill.setPictureData(pd);
ppt.write(out);
out.close();
}
After that I tried to create a PPT file using the generated POTX file but
But it's giving error. I am trying bellow code for this.
And the code is
private static void GeneratePPTXUsingPOTX() throws FileNotFoundException, IOException {
File imgFile = new File(System.getProperty("user.dir")+"/src/resources/images/TestSameChnl_001_t.jpeg");
File potx_File = new File(System.getProperty("user.dir") + "/src/resources/Examples/layout.potx" );
File pptx_File = new File(System.getProperty("user.dir") + "/src/resources/Examples/PPTWithTemplate.pptx" );
File movieFile = new File(System.getProperty("user.dir") + "/src/resources/movie/Dummy.mp4");
FileInputStream ins = new FileInputStream(potx_File);
FileOutputStream out = new FileOutputStream(pptx_File);
HSLFSlideShow ppt = new HSLFSlideShow(ins);
List<HSLFSlide> slideList = ppt.getSlides();
int movieIdx = ppt.addMovie(movieFile.getAbsolutePath(), MovieShape.MOVIE_MPEG);
HSLFPictureData pictureData = ppt.addPicture(imgFile, PictureData.PictureType.JPEG);
MovieShape shape = new MovieShape(movieIdx, pictureData);
shape.setAnchor(new java.awt.Rectangle(300,225,420,280));
slideList.get(0).addShape(shape);
shape.setAutoPlay(true);
ppt.write(out);
out.close();
}
And the exception which is coming is as fallows:
java.lang.NullPointerException
at org.apache.poi.hslf.usermodel.HSLFPictureShape.afterInsert(HSLFPictureShape.java:185)
at org.apache.poi.hslf.usermodel.HSLFSheet.addShape(HSLFSheet.java:189)

How to populate XML node values in Grid view in Asp.net?

I am using a thirdparty webservice. I got the response in XML format.
Now, i have to show the XML node values in grid view.
The following code i tried so far.
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
//Label2.Text = reader.ReadToEnd();
XmlDocument xml = new XmlDocument();
xml.Load(reader);
XmlNamespaceManager ns = new XmlNamespaceManager(xml.NameTable);
ns.AddNamespace("ms", "http://webservices.amazon.com/AWSECommerceService/2005-10-05");
XmlNode image = xml.SelectSingleNode("//ms:URL", ns);
XmlNode FormattedPrice = xml.SelectSingleNode("//ms:FormattedPrice", ns);
Now, i want to show the values of XMLnode value in grid view.
Please inform me, if you need more information.
Thanks in advance.
You can use an XMLDataSourcefor that:
http://www.codeproject.com/Articles/10898/Introduction-to-XMLDataSource-control-in-ASP-NET-2
Best regards.
Solution:
Instead of Get the HttpResponse in xmldocument.
I used XNamespace and XDocument.
XNamespace ns = "http://webservices.amazon.com/AWSECommerceService/2005-10-05"; // Linq
XDocument xd = XDocument.Load(response.GetResponseStream());
Then Use Linq to Read all Vlaues. Example:
var Image = xd.Descendants(ns + "Items").Elements(ns + "Item").Select(img => img.Elements(ns + "MediumImage").Select(img1 => (string)img1.Element(ns + "URL")).FirstOrDefault() ?? "Null").ToList();