Add PDFObject from already created pdf element - asp.net-mvc

I have a pdf element that I am returning as a string base64 element since it is an MVC Web Application and the files live on a server. I am currently using PDFObject and pdf.js to try and view this PDF in the browser. However, I seem unable to display the PDF, unless I pass a url, which won't work when I put this application in IIS on a server.
So is there a way to have my embedded pdf with the src="{my base 64 string}, and then wrap the PDFObject around that? If not, is there a way, via PDFObject, to use a base64 string instead of a url?
Also, this is in IE 11
UPDATE
Here is my controller
public ActionResult GetPDFString(string instrumentType, string booktype, string book, string startpage, string EndPage)
{
LRS_Settings settings = ctxLRS.LRS_Settings.FirstOrDefault();
string root = settings.ImagePathRoot;
string state = settings.State;
string county = settings.County;
g_filePath = #"\\10.20.170.200\Imaging\GA\075\Daily\" + instrumentType + "\\" + book + "\\";
//g_filePath = #"\\10.15.100.225\sup_court\Imaging\GA\075\Daily\" + instrumentType + "\\" + book + "\\";
byte[] file = imgConv.ConvertTifToPDF(g_filePath, booktype, book, startpage, EndPage);
var ms = new MemoryStream(file);
var fsResult = new FileStreamResult(ms, "application/pdfContent");
return fsResult;
//return imgConv.ConvertTifToPDF(g_filePath, booktype, book, startpage, EndPage);
}
Here is my jquery
var options = {
pdfOpenParams: {
navpanes: 1,
toolbar: 0,
statusbar: 0,
pagemode: 'none',
pagemode: "none",
page: 1,
zoom: "page-width",
enableHandToolOnLoad: true
},
forcePDFJS: true,
PDFJS_URL: "/PDF.js/web/viewer.html"
}
PDFObject.embed("#Url.Action("GetPDFString", "DocumentView", new { instrumentType = ViewBag.instrumentType, BookType = Model.BookType, Book = ViewBag.Book, StartPage = ViewBag.StartPage, EndPage = ViewBag.endPage, style = "height:100%; width100%;" })", "#PDFViewer", options);
The problem is now, instead of showing the PDF inside of #PDFViewer, it is trying to download the file. Could someone please assist me on the final piece to the puzzle. This is driving me crazy.

Have you tried to use just the standard html to do this instead?
Controller Action
public ActionResult GetAttachment(string instrumentType, string booktype, string book, string startpage, string EndPage)
{
var fileStream = new FileStream(Server.MapPath("~/Content/files/sample.pdf"),
FileMode.Open,
FileAccess.Read
);
var fsResult = new FileStreamResult(fileStream, "application/pdf");
return fsResult;
}
In your view
<div id="PDFViewer">
<embed src="#Url.Action("GetAttachment", "DocumentView", new { instrumentType = ViewBag.instrumentType, BookType = Model.BookType, Book = ViewBag.Book, StartPage = ViewBag.StartPage, EndPage = ViewBag.endPage })" width="100%" height="100%" type="application/pdf"></embed>
</div>
Would this suit your requirements rather than using PDFObject?

Be sure to set the content disposition header to inline or the browser will try to download the file rather than render it in the viewport.
See Content-Disposition:What are the differences between "inline" and "attachment"?
As far as PDFObject versus plain HTML, for troubleshooting I always recommend trying static markup (no JS) to display the same PDF. If it works there, the problem may lie with PDFObject (in this case, PDFObject's handling of Base64 strings). If the PDF is not properly rendered via plain markup, the issue probably lies with your file/Base64.
You can grab a copy of static markup from the PDFObject static markup generator: http://pdfobject.com/generator
(I should add that I can't speak to PDF.js' handling of Base64 strings...)

Related

Download PDF file and show directly in browser in MVC Project

I am calling a Web API from MVC project. The Web API is returning PDF file that I want to show directly in the browser after clicking on a button. My problem is when I click on the link, it downloads the pdf file and shows the icon at the left bottom corner side and I have to click on it and to open the PDf in acrobat. How I can make it the way that by clicking the link it open the pdf directly in the browser?
This is my code in MVC project that open the pdf:
[HttpGet]
public FileResult openPdf(string name)
{
byte[] pdfByte = DownloadFile();
return File(pdfByte, "application/pdf", name);
}
internal byte[] DownloadFile()
{
string serverUrl = "http://localhost/GetPdf?Number=3671";
var client = new System.Net.WebClient();
client.Headers.Add("Content-Type", "application/pdf");
return client.DownloadData(serverUrl);
}
This is the method in my Web API that returns pdf:
public HttpResponseMessage GetPdfNameByRemRef(string RemoteRefNumber)
{
var stream = new MemoryStream();
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.GetBuffer())
};
byte[] fileBytes = System.IO.File.ReadAllBytes(#"C:\Pdf\CreditApplication_08192006_102714AM_et montis.pdf");
response.Content = new ByteArrayContent(fileBytes);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = customerInfo.Application_Filename;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
You can try to add Content-Disposition header with value inline.
Response.AddHeader("Content-Disposition", "inline;filename=fileName.pdf");
However, the behavior can differ on different browsers and on file types you are serving. If Content-Disposition is set to inline the browser will try to open the file within the browser, but it may fail if the file type is unknown (ex. .rar, .zip, .pdf /when pdf reader plugin is missing/, if the browser is old .. etc.).

Image won't display MVC5

Hello evryone (im using MVC5),
i generate image from Chart in Html Helper Extension
public static string GetUrlFromChart(this HtmlHelper helper, Chart chart)
{
lock (obj)
{
string path = HttpContext.Current.Server.MapPath("~/App_Data/graphs/");
string filename = path + Guid.NewGuid() + ".jpg";
chart.ToWebImage("jpg").Save(filename);
return filename;
}
}
by viewmodel i send data to view and i tried to show them to user.
<img src="#Html.GetUrlFromChart(#Model.my_chart)" width="400" height="250"/>
Image generate properly, in correct path, but application cannot show me it,
its only white rectangle
when i copy image source to windows explorer.
i get that image.
but it seems to wont work with
<img></img>
anyone know how to display System.Web.Helpers.Chart like image, or display data like chart ?
Hello mate you should return the image rather than the file path
I don't know about this Chart object so I just change the code to a generic one
change your code to:
public static ActionResult GetUrlFromChart()
{
lock (obj)
{
string path = HttpContext.Current.Server.MapPath("~/App_Data/graphs/");
string filename = path + Guid.NewGuid() + ".jpg";
var image = chart.ToWebImage("jpg");
//save your image.
return File(image.GetBytes(), "image/jpeg");
}
}
in the view:
<img src="#Url.Action("GetUrlFromChart", "Yourcontrollername")"/>

Reading remote text file with AIR, spaces and links

I have a text file(txt) in my web server. I will read the file contents and show it to user. The problem is that it does not show line separations and spaces the right way. Also i will need to activate possible links. For example if there is http://www.google.com then user can just click on the link and default browser opens it.
So far i have this:
var fileContents:String;
try{
var myLoader:URLLoader = new URLLoader();
myLoader.addEventListener(Event.COMPLETE, onFileLoaded);
myLoader.load(new URLRequest("http://my.website.com/test.txt"));
function onFileLoaded(e:Event):void
{
fileContents = String(e.currentTarget.data);
var alertMessage = fileContents;
I have done this same thing in java, but I am not so familiar with ActionScript.
Java code:
URL url = new URL(getString(R.string.url));
BufferedReader r = new BufferedReader(new InputStreamReader(
url.openStream(), "UTF-8"));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
total.append(System.getProperty("line.separator"));
}
str = total.toString();
r.close();
return str;
Links in java:
final SpannableString s = new SpannableString(sUrl);
Linkify.addLinks(s, Linkify.WEB_URLS);
You might consider using the Text Layout Framework (TLF) from Adobe. You can import the text as HTML and it will create clickable links for any URL's found in the text. TLF is a bit unwieldy, but very powerful.
private var myTextFlow:TextFlow = TextConverter.importToFlow(sourceText, TextConverter.TEXT_FIELD_HTML_FORMAT);
If you are using Flex 4, can assign the resulting TextFlow object to one of the text components:
<s:RichText textFlow="{myTextFlow}" />
In an Actionscript project, you have to do a little more work to use the TextFlow. TLF uses an MVC approach. The TextFlow serves as the model, you can use a Sprite for the view, and a ContainerController as the controller:
private var container:Sprite = new Sprite();
addChild(container);
private var controller:ContainerController = new ContainerController(container, 800,600);
myTextFlow.flowComposer.addController(controller);
myTextFlow.flowComposer.updateAllControllers();

Easiest way of porting html table data to readable document

Ok,
For the past 6 months i've been struggeling to build a system that allows user input in form of big sexy textareas(with loads of support for tables,list etc). Pretty much enables the user to input data as if it were word. However when wanting to export all this data I haven't been able to find a working solution...
My first step was to try and find a reporting software that did support raw HTML from the data source and render it as normal html, worked perfectly except that the keep together function is awful, either data is split in half(tables,lists etc) which I dont want. Or report always skips to the next page to avoid this, ending up in 15+ empty pages within the final document.
So Im looking for some kind of tip/direction to what would be the best solution to export my data into a readable document(pdf or word pref).
What I got is the following data breakdown, where data is often raw html.
-Period
--Unit
---Group
----Question
-----Data
What would be the best choice? Trying to render html to pdf or rtf? I need tips :(
And also sometimes the data is 2-3 pages long with mixed tables lists and plain text.
I would suggest that you try to keep this in the browser, and add a print stylesheet to the HTML to make it render one way on the screen and another way on paper. Adding a print stylesheet to your HTML is as easy as this:
<link rel="stylesheet" media="print" href="print.css">
You should be able to parse the input it with something like Html Agility Pack and transform it (i.e. with XSLT) to whatever output format you want.
Another option is to write HTML to the browser, but with Content-Type set to a Microsoft Word-specific variant (there are several to choose from, depending on the version of Word you're targeting) should make the browser ask if the user wants to open the page with Microsoft Word. With Word 2007 and newer you can also write Office Open XML Word directly, since it's XML-based.
The content-types you can use are:
application/msword
For binary Microsoft Word files, but should also work for HTML.
application/vnd.openxmlformats-officedocument.wordprocessingml.document
For the newer "Office Open XML" formats of Word 2007 and newer.
A solution you could use is to run an application on the server using System.Diagnostics.Process that will convert the site and save it as a PDF document.
You could use wkhtmltopdf which is an open source console program that can convert from HTML to PDF or image.
The installer for windows can be obtained from wkhtmltox-0.10.0_rc2 Windows Installer (i368).
After installing wkhtmltopdf you can copy the files in the installation folder inside your solution. You can use a setup like this in the solution:
The converted pdf's will be saved to the pdf folder.
And here is code for doing the conversion:
var wkhtmltopdfLocation = Server.MapPath("~/wkhtmltopdf/") + "wkhtmltopdf.exe";
var htmlUrl = #"http://stackoverflow.com/q/7384558/750216";
var pdfSaveLocation = "\"" + Server.MapPath("~/wkhtmltopdf/pdf/") + "question.pdf\"";
var process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.FileName = wkhtmltopdfLocation;
process.StartInfo.Arguments = htmlUrl + " " + pdfSaveLocation;
process.Start();
process.WaitForExit();
The htmlUrl is the location of the page you need to convert to pdf. It is set to this stackoverflow page. :)
Its a general question, but two things come to mind the Visitor Pattern and Changing the Mime Type.
Visitor Pattern
You can have two seperate rendering techniques. This would be up to your implementation.
MIME Type
When the request is made write date out in the Response etc
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "utf-16";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.doc", filename));
HttpContext.Current.Response.ContentType = "application/msword";
HttpContext.Current.Response.Write("-Period");
HttpContext.Current.Response.Write("/n");
HttpContext.Current.Response.Write("--Unit");
HttpContext.Current.Response.Write("/n");
HttpContext.Current.Response.Write("---Group");
HttpContext.Current.Response.Write("/n");
HttpContext.Current.Response.Write("----Question");
HttpContext.Current.Response.Write("/n");
HttpContext.Current.Response.Write("-----Data");
HttpContext.Current.Response.Write("/n");
HttpContext.Current.Response.End();
Here is another option, use print screens (Although it doesnt take care of scrolling, I think you should be able to build this in). This example can be expanded to meet the needs of your business, although it is a hack of sorts. You pass it a URL it generates an image.
Call like this
protected void Page_Load(object sender, EventArgs e)
{
int screenWidth = Convert.ToInt32(Request["ScreenWidth"]);
int screenHeight = Convert.ToInt32(Request["ScreenHeight"]);
string url = Request["Url"].ToString();
string bitmapName = Request["BitmapName"].ToString();
WebURLToImage webUrlToImage = new WebURLToImage()
{
Url = url,
BrowserHeight = screenHeight,
BrowserWidth = screenWidth,
ImageHeight = 0,
ImageWidth = 0
};
webUrlToImage.GenerateBitmapForUrl();
webUrlToImage.GeneratedImage.Save(Server.MapPath("~") + #"Images\" +bitmapName + ".bmp");
}
Generate an image from a webpage.
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using System.IO;
public class WebURLToImage
{
public string Url { get; set; }
public Bitmap GeneratedImage { get; private set; }
public int ImageWidth { get; set; }
public int ImageHeight { get; set; }
public int BrowserWidth { get; set; }
public int BrowserHeight { get; set; }
public Bitmap GenerateBitmapForUrl()
{
ThreadStart threadStart = new ThreadStart(ImageGenerator);
Thread thread = new Thread(threadStart);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
return GeneratedImage;
}
private void ImageGenerator()
{
WebBrowser webBrowser = new WebBrowser();
webBrowser.ScrollBarsEnabled = false;
webBrowser.Navigate(Url);
webBrowser.DocumentCompleted += new
WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
while (webBrowser.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
webBrowser.Dispose();
}
void webBrowser_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser webBrowser = (WebBrowser)sender;
webBrowser.ClientSize = new Size(BrowserWidth, this.BrowserHeight);
webBrowser.ScrollBarsEnabled = false;
GeneratedImage = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height);
webBrowser.BringToFront();
webBrowser.DrawToBitmap(GeneratedImage, webBrowser.Bounds);
if (ImageHeight != 0 && ImageWidth != 0)
GeneratedImage =
(Bitmap)GeneratedImage.GetThumbnailImage(ImageWidth, ImageHeight,
null, IntPtr.Zero);
}
}

ASP.NET MVC Converting HTML page containing Form to PDF

I'm working on a view in a ASP.NET MVC 2 application. This view will contain fixed text but it will also contain text boxes, checkboxes, and perhaps a Telerik Grid that can be updated from a user. ** This form isn't in a fixed format since there could be a 1...N number of items listed. ** We want to be able to print this view to a PDF. The PDF we want to print off will just look like the view but preferrably it will have just the text from the text boxes and not the text box border. The same goes for the Telerik grid.
How to you recommend I go about doing this? Preferrably I like to see a print button on the view that will directly print it to a PDF. i.e. No secondary window that pops up. That may not be a deal breaker though.
** Update **
Let's forget about the form elements for a second. Let's say my view is displayed in the same format that I want in my PDF. How to print that view into a PDF?
The simplest way to do this is to create a separate Print action that returns a FileResult of a PDF generated on the fly with a library like iTextSharp
You would not be able to completely reuse the HTML form as is in the PDF document, since you don't want to use text boxes, but your could generate an HTML view that matches your desired PDF and then use iTextSharp to save that HTML as a PDF.
Alternatively, you could use the iTextSharp library to build up a PDF from scratch and have much more control, but this might be a bit more difficult.
From your controller the simplest way to return the PDF without a secondary window is to have your action method return:
return File(iTextSharpByteArray, "application/pdf", "nameOfFileUserWillDownload.pdf");
Most free open source PDF .dlls are difficult to programatically create HTML in a PDF (mostly due to limited support for HTML tags etc.).
A paid for one is much more simple eg. http://www.html-to-pdf.net/ With this you can just point the converter to a template page and it will work. Even javascript and Flash content etc will also be parsed and included (statically) in the final PDF.
You can make an rdlc report as desired and call at the click of a print button/link in your view, through a controller function.
in your view
Html.ActionLink("Print", "Print", new { id = c.sid })
in you controller
public ActionResult Print(int id)
{
string unitc = Session["unit"].ToString();
ctid= unitc;//class level variable used in detailreport function
brid = id;//class level variable used in detailreport function
return DetailsReport();
}
FileContentResult DetailsReport()
{
LocalReport localReport = new LocalReport();
localReport.ReportPath = Server.MapPath("~/Reports/rptinvoice.rdlc");
InvoiceRepository ivr = new InvoiceRepository();
if (localReport.DataSources.Count > 0)
{
localReport.DataSources.RemoveAt(0);
localReport.DataSources.RemoveAt(1);
localReport.DataSources.RemoveAt(2);
}
localReport.Refresh();
ReportDataSource reportDataSource = new ReportDataSource("DataSet1", ivr.GetSales(ctid));
localReport.SetParameters(new ReportParameter[] { new ReportParameter("ct_id", ctid.ToString()), new ReportParameter("ct_br_id", brid.ToString()) });
localReport.DataSources.Add(reportDataSource);
string reportType = "PDF";
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>PDF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.2in</MarginTop>" +
" <MarginLeft>0.05in</MarginLeft>" +
" <MarginRight>0.05in</MarginRight>" +
" <MarginBottom>0.1in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
localReport.EnableExternalImages = true;
//Render the report
try
{
renderedBytes = localReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
}
catch (Exception Ex)
{
ViewData["ResultP"] = Ex.Message + ",<br>" + Ex.InnerException.Message;
throw;
}
return File(renderedBytes, mimeType);
}

Resources