ASP.NET Download Aspose PDF with embedded BMP - c#

I need to render a BMP to a PDF using Aspose and download it.
The downloaded PDF is corrupt and Adobe will not open it. The saved to file PDF is fine and opens. Anyone know why the PDF from download is corrupted?
protected void ASPxButton1_OnClick(object sender, EventArgs e)
{
WebsiteToImage websiteToImage = new WebsiteToImage(HttpContext.Current.Request.Url.AbsoluteUri, #"C:\Temp\Test.jpg");
var generate = websiteToImage.Generate();
// Create a MemoryStream object from image Byte array
MemoryStream ms = new MemoryStream();
websiteToImage.Bitmap.Save(ms, ImageFormat.Jpeg);
// create a PDF object
Pdf pdf = new Pdf();
// create a section and add it to pdf document
Aspose.Pdf.Generator.Section MainSection = pdf.Sections.Add();
//Add the radio form field to the paragraphs collection of the section
// create an image object
Aspose.Pdf.Generator.Image sample_image = new Aspose.Pdf.Generator.Image();
// specify the image file path information
//sample_image.ImageInfo.File = #"d:/pdftest/untitled.bmp";
sample_image.ImageInfo.ImageStream = ms;
// specify the image file type
sample_image.ImageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Bmp;
// specify the image width information equal to page width
sample_image.ImageInfo.FixWidth = MainSection.PageInfo.PageWidth - MainSection.PageInfo.Margin.Left - MainSection.PageInfo.Margin.Right;
// specify the image Height information equal to page Height
sample_image.ImageInfo.FixWidth = MainSection.PageInfo.PageHeight - MainSection.PageInfo.Margin.Top - MainSection.PageInfo.Margin.Bottom;
// create bitmap image object to load image information
Bitmap myimage = websiteToImage.Bitmap;
// check if the width of the image file is greater than Page width or not
if (myimage.Width > MainSection.PageInfo.PageWidth)
// if the Image width is greater than page width, then set the page orientation to Landscape
MainSection.IsLandscape = true;
else
// if the Image width is less than page width, then set the page orientation to Portrait
MainSection.IsLandscape = false;
// add image to paragraphs collection of section
MainSection.Paragraphs.Add(sample_image);
// save the resultant PDF
pdf.Save(#"C:\Temp\Test.pdf");
pdf.Save(ms);
byte[] bytes = ms.GetBuffer();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + Operator.Emplid + "Gudiance.pdf");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.End();
ms.Close();

It appears that you are using a legacy Aspose.Pdf.generator approach, so in order to accomplish your requirements, we recommend you to please try using new Document Object Model of Aspose.Pdf namespace. Please try using following code snippet.
// create a PDF object
Document pdf = new Document();
// create a section and add it to pdf document
Aspose.Pdf.Page MainSection = pdf.Pages.Add();
//Add the radio form field to the paragraphs collection of the section
// create an image object
Aspose.Pdf.Image sample_image = new Aspose.Pdf.Image();
// specify the image file path information
sample_image.File = #"C:\pdftest\OutOfMemoryDemo\OutOfMemoryDemo\Sample.bmp";
// specify the image width information equal to page width
sample_image.FixWidth = MainSection.PageInfo.Width - MainSection.PageInfo.Margin.Left - MainSection.PageInfo.Margin.Right;
// specify the image Height information equal to page Height
sample_image.FixWidth = MainSection.PageInfo.Height - MainSection.PageInfo.Margin.Top - MainSection.PageInfo.Margin.Bottom;
// create bitmap image object to load image information
System.Drawing.Bitmap myimage = new System.Drawing.Bitmap(#"C:\pdftest\OutOfMemoryDemo\OutOfMemoryDemo\Sample.bmp");
// check if the width of the image file is greater than Page width or not
if (myimage.Width > MainSection.PageInfo.Width)
// if the Image width is greater than page width, then set the page orientation to Landscape
MainSection.PageInfo.IsLandscape = true;
else
// if the Image width is less than page width, then set the page orientation to Portrait
MainSection.PageInfo.IsLandscape = false;
// add image to paragraphs collection of section
MainSection.Paragraphs.Add(sample_image);
MemoryStream stream = new MemoryStream();
// save the resultant PDF
pdf.Save(stream);
StreamReader reader = new System.IO.StreamReader(Request.InputStream);
String Data = reader.ReadToEnd();
this.Title = Data;
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
Response.Charset = "UTF-8";
Response.AddHeader("Accept-Header", stream.Length.ToString());
Response.AddHeader("Content-Length", stream.Length.ToString());
Response.AddHeader("Expires", "0″");
Response.AddHeader("Pragma", "cache");
Response.AddHeader("Cache-Control", "private");
Response.AddHeader("content-disposition", String.Format("inline;filename={0}", "article" + "docId"+ ".pdf"));
Response.ContentType = "application/pdf";
Response.AddHeader("Accept-Ranges", "bytes");
Response.BinaryWrite(stream.ToArray());
Response.Flush();
Response.End();
PS, My name is Nayyer and I am developer evangelist at Aspose.

Related

Poor image quality after added to PDF with itextsharp

I want to create a portrait gallery with some photos. In order to achieve this, I add everything I need in a panel and then I get the visual of this panel to add it in a PDF.
My problem is that I managed to create the PDF containing the image, but it is bad quality.
Example 1
Example 2
We see that the outline of peoples is not clear, while in the original photos the outline is very clear.
iTextSharp.text.Document doc = new iTextSharp.text.Document();
panelTombi.AutoScrollPosition = new Point(0, 0);
panelTombi.AutoSize = true;
panelTombi.Refresh();
int width = panelTombi.Width;
int height = panelTombi.Height;
Bitmap MemoryImage = new Bitmap(width, height);
panelTombi.DrawToBitmap(MemoryImage, new System.Drawing.Rectangle(0, 0, width, height));
iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance((System.Drawing.Image)MemoryImage, System.Drawing.Imaging.ImageFormat.Jpeg);
image1.ScaleToFit(doc.PageSize);
image1.SetAbsolutePosition(0, PageSize.A4.Height - image1.ScaledHeight - doc.TopMargin);
MemoryImage.Save(Path.GetDirectoryName(sfd.FileName) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(sfd.FileName) + ".jpeg");
//Save pdf file
PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
doc.Open();
doc.Add(image1);
doc.Close();
As you can see, the image is also saved.
Could you tell me how to fix this image quality problem on the PDF file?
Thank you

How to give custom size to PdfSharp generated Pdf

I was trying to generate a pdf from HTML which containing a table using PdfSharp and HTMLRenderer. The following shows the code.
pdf = PdfGenerator.GeneratePdf(html, PageSize.A3);
byte[] fileContents = null;
using (MemoryStream stream = new MemoryStream())
{
pdf.Save(stream, true);
fileContents = stream.ToArray();
return new FileStreamResult(new MemoryStream(fileContents.ToArray()), "application/pdf");
}
Is there any possibility for me to provide a custom size to the PDF and change the orientation of the page. I am using a memory stream to show the PDF directly on the browser display.
You can use the PdfGenerateConfig parameter of the GeneratePdf method to specify a custom page size using the ManualPageSize property.
Use the PageOrientation to get standard page sizes in landscape.
Code from comment:
var config = new PdfGenerateConfig();
config.PageOrientation = PageOrientation.Landscape;
config.ManualPageSize = new PdfSharp.Drawing.XSize(1080, 828);
pdf = PdfGenerator.GeneratePdf(html, config);
I just put this way:
var config = new PdfGenerateConfig()
{
MarginBottom = 100,
MarginLeft = 20,
MarginRight = 20,
MarginTop = 100,
PageSize = PageSize.A4
};
PdfDocument pdf = PdfGenerator.GeneratePdf(html, config);
If I'm not mistaken, PageSize.A3 is not an enum but Rectangle value. So instead of passing predefined Rectangle you can provide your own, for example:
new Rectangle(1191, 842) // for album A3
new Rectangle(842, 595) // for album A4
and so on...

Excel sheet does not display exported chart image - ASP.NET

I have a web page in my website that allows me to download the chart from that page and add it to an excel sheet. However, a red x button with the words: "this image cannot currently be displayed" is shown in place of the chart. I have tried many solutions online but all of them show the same outcome.
Here are my codes:
protected void ExcelDl_Click(object sender, EventArgs e) {
string tmpChartName = "test2.jpg";
string imgPath = HttpContext.Current.Request.PhysicalApplicationPath + tmpChartName;
Chart1.SaveImage(imgPath);
string imgPath2 = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/" + tmpChartName);
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;");
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
string headerTable = #"<Table><tr><td><img src='" + imgPath2 + #"' \></td></tr></Table>";
Response.Write(headerTable);
Response.Write(sw.ToString());
Response.End();
}
Any form of help will be greatly appreciated. Also, do note that I have added the required codes in my Web.config.
We have tried your program and here it’s working fine. Excel downloaded along with image. I have installed in iis and tried with many client machine and it was working fine.
Not sure what’s going on your end. The problem might be wrong image path reference will cause this problem. Print image URL and make sure whether it is correct or not.
Alternate method: instead of using html tags inside the excel cell use XML closing method to render the image inside the excel cell.
Here I have added sample code for the Closed XML methods to render the image in excel. to use this code need to refer the following DLLs
1. ClosedXML.dll
2. WindowsCore.dll
3. DocumentFormat.OpenXML.dll
4. PresentationCore.dll
Reference Link for Closed XML methods: https://closedxml.codeplex.com/
using (XLWorkbook wb = new XLWorkbook())
{
IXLWorksheet WorkSheet = new IXLWorksheet();
string LogoPath = Server.MapPath("~/App_Themes/Images/logonew.png");
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(LogoPath);
if (bitmap != null)
{
var stream = new System.IO.MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
if (stream != null)
{
stream.Position = 0;
XLPicture pic = new XLPicture
{
NoChangeAspect = true,
NoMove = true,
NoResize = true,
ImageStream = stream,
Name = "Logo",
EMUOffsetX = 4,
EMUOffsetY = 6
};
XLMarker fMark = new XLMarker
{
ColumnId = 1,
RowId = 1
};
pic.AddMarker(fMark);
WorkSheet.AddPicture(pic);
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=test.xls");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
Please check and let me know your comments.

download multiple pdf

I am trying to download multiple pdf's as attachments in my asp.net application.I have created some templates and filling values using pdfstamper(itextsharp). I am able to fill the values but not able to download.
private void FillForm(string path, DataTable BridgeValues, DataTable Comments, DataTable Maintenance,string Newfilename)
{
try
{
string pdfTemplate = path;
string newFile = Newfilename;
string Pathser = "";
if (!System.IO.Directory.Exists(Server.MapPath(#"~/PDF/")))
{
System.IO.Directory.CreateDirectory(Server.MapPath(#"~/PDF/"));
}
if (Directory.Exists(Server.MapPath(#"~/PDF/")))
{
Pathser = Server.MapPath(#"~/PDF/" + Newfilename);
}
System.IO.MemoryStream mStream = new System.IO.MemoryStream();
// create a new PDF reader based on the PDF template document
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(Pathser, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
DataColumn dc = null;
for (int i = 0; i < BridgeValues.Columns.Count - 1; i++)
{
dc = BridgeValues.Columns[i];
pdfFormFields.SetField(dc.ColumnName.ToString(), BridgeValues.Rows[0][dc].ToString());
}
pdfStamper.FormFlattening = true;
// close the pdf
pdfStamper.Close();
////Response.ContentType = "application/octet-stream";
Response.ContentType = "application/pdf";
////Response.AddHeader("Content-Disposition", "attachment; filename=Report.pdf");
Response.AddHeader("Content-Disposition", "attachment; filename=" + Newfilename + "");
////Response.BinaryWrite(mStream.ToArray());
Response.TransmitFile(Server.MapPath(("~/PDF/"+ Newfilename)));
Response.Clear();
Response.End();
}
catch (System.Threading.ThreadAbortException lException)
{
// do nothing
}
}
First time I tried to create one pdf ,it worked but later when I tried to download multiple files it gave an execption.
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
I don't think you can download multiple files by making one request and returning a collection from the action. I would suggest that it you need to allow user to download multiple files you ZIP them and stream the archive down to the browser.
Here is an example of zipping multiple files: http://devpinoy.org/blogs/keithrull/archive/2008/01/25/how-to-create-zip-files-in-c-with-sharpziplib-ziplib.aspx

Modifying a PDF using iTextSharp

I have a HttpModule that intercepts requests for PDF documents and I would like to add a date to the PDF and stream back to the client.
My code so far is
context.Response.ClearContent();
using (MemoryStream ms = new MemoryStream())
{
PdfReader reader = new PdfReader(document.Url + "&a=1");
PdfStamper stamper = new PdfStamper(reader, ms);
// *** Modify PDF here
stamper.Close();
context.Response.ContentType = "application/pdf";
context.Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
context.Response.OutputStream.Flush();
context.Response.OutputStream.Close();
context.Response.Flush();
context.Response.End();
}
HttpContext.Current.ApplicationInstance.CompleteRequest();
The code above works fine, but as soon as I try to modify the PDF I get a PDF Reader error 'The file is damaged and cannot be repaired', for example
TextField textField = new TextField(stamper.Writer, new Rectangle(0, 1000, 90, 600), name);
textField.Font = FontFactory.GetFont(FontFactory.HELVETICA, DEFAULT_FONT_SIZE, Font.NORMAL).BaseFont;
textField.FontSize = DEFAULT_FONT_SIZE;
textField.Rotation = 90;
PdfFormField field = textField.GetTextField();
stamper.AddAnnotation(field, page);
Does anyone know how I can solve this issue?
You continue sending stuff after the pdf, add
context.Response.End();
after:
context.Response.Flush();
Now you will send only the pdf, instead of the whole page. This sometimes fixes this issue.
You are also reading the buffer twice:
context.Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
try to add
byte[] bytes = ms.ToArray();
and then
context.Response.OutputStream.BinaryWrite(bytes);

Categories

Resources