Three steps I am following.
Create PDF in one view.
Store in database in byte[] form which column is varbinary(max)
Retrieve from database and show as PDF when user click.
Creating PDF:
public byte[] PDF(List<DeliveryOrderDetail> deliveryOrdList)
{
byte[] result;
string headingText = "Guide";
try
{
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document();
PdfWriter.GetInstance(doc, ms).CloseStream = false;
PdfPTable pdfTab = new PdfPTable(3);
Paragraph heading = new Paragraph(headingText, new Font(Font.TIMES_ROMAN, 18f, Font.NORMAL, Color.BLACK));
Paragraph ItemDetail = new Paragraph("Items in Delivery Order Box:", new Font(Font.TIMES_ROMAN, 12f, Font.NORMAL, Color.BLACK));
heading.Alignment = Element.ALIGN_CENTER;
ItemDetail.Alignment = Element.ALIGN_CENTER;
doc.Open();
doc.Add(heading);
pdfTab.HorizontalAlignment = 1;
pdfTab.SpacingBefore = 20f;
pdfTab.SpacingAfter = 20f;
pdfTab.AddCell("ItemName");
pdfTab.AddCell("BoxId");
pdfTab.AddCell("Manufacturer");
doc.Add(ItemDetail);
foreach (var item in deliveryOrdList)
{
pdfTab.AddCell(item.Name);
pdfTab.AddCell(item.Id.ToString());
pdfTab.AddCell(item.Manufacturer);
}
doc.Add(pdfTab);
doc.Close();
result = ms.GetBuffer();
}
return result;
}
catch(Exception e )
{
}
return null;
}
Storing result which is byte[] into database table with db.savechanges();
On image click :
var pdf will get the database field which contains binary data
jQuery: when image is clicked go to controller
<script type="text/javascript">
$(document).ready(function () {
$('.Pdf').click(function () {
var pdf = $(this).closest('tr').find('td:eq(0) input').val();;
alert(pdf);
$.ajax({
url: "/ship/PDF",
type: "POST",
dataType: "json",
data:JSON.stringify({ pdf: pdf }),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8"
})
})
})
</script>
In Controller: Following method is written which accept as string :
[HttpPost]
public ActionResult PDF(string pdf)
{
try
{
byte[] byteInfo = System.Text.Encoding.UTF8.GetBytes(pdf);
MemoryStream ms = new MemoryStream();
workStream.Write(byteInfo, 0, byteInfo.Length);
workStream.Position = 0;
return new FileStreamResult(ms, "application/pdf");
}
catch (Exception _Exception)
{
}
return null;
}
Here I am unable to see pdf.in browser when image is clicked. I have tried all options but unable to get it. If I write it in file. PDF will not get opened
System.IO.File.WriteAllBytes(@"D:\personal\testpdf.pdf", byteInfo);