Printing a pdf with mvc - javascript

I have pdfs being generated on a website, and am trying to implement a print button for that pdf. I know about being able to print a specific div and it's associated html, but is it possible to have a button that opens up a pdf generated by my website in the chrome print preview without having to download it first?
I appreciate any help.

The pdf file that is generated on the server has to come down to the client (i.e. downloaded) so cannot really print something that is not on the client.
In case you want to bypass the file saving action (explicitly done by the user) and go directly to print preview, you can try something like this before returning the file:
var pdfFileName = "Some Filename";
if (Request.Browser.Browser == "InternetExplorer" || Request.Browser.Browser == "IE")
{
Response.AppendHeader("content-disposition", #"attachment;filename=""" + pdfFileName + #".pdf""");
}
else
{
Response.AppendHeader("content-disposition", #"inline;filename=""" + pdfFileName + #".pdf""");
}
byte[] pdfBytes = ... // get the file data into this variable
return File(pdfBytes, "application/pdf")

I don't think so. The PDF still has to be downloaded and rendered by the PDF library before it can be printed, unlike HTML which is the browser's native format.

Use Datatables.Net Export tables

Related

Printing multiple files through javascript

I need to print multiple files using javascript. Print single file works fine but as soon as I try and print multiple files, I get only one printed.
My javacript is as under
function LoadPrint() {
if (document.getElementById("pdf").src !== "") {
var frm = document.getElementById("pdf").contentWindow;
frm.focus();
frm.print();
}
return false;
}
and I call it from c# as below
foreach (var str in filenames)
ClientScript.RegisterStartupScript(this.GetType(), "Print", "LoadPdfFile('" + "/Templates/" + str + "');", true);
How can I tell RegisterStartupScript to wait until the file is printed?
If you have a component to generate a pdf, you'll have the functionality to create one pdf by merging many.
I suggest you write a method to create a new pdf with a pagebreak between each one and let the server handle it instead of the client

How do I return a file to the user?

I am trying to return a file to the user.
"GetExcel" appears to work and in debug I can see that "ba" has data.
The method completes BUT nothing appears to be returned to the browser - I am hoping to see the file download dialog.
C#
public FileResult GetExcel()
{
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
ws.Cells["A1"].Value = "LBHERE";
var ba = pck.GetAsByteArray();
return File(ba, "text/plain", "testFile.txt");
}
}
Javascript
function clickedTest() {
alert("Test clicked");
$.get(myPath + "/Employee/GetExcel", { }, function (data) {
})
};
jQuery's $.get() function pulls data from a webpage into your client-side scripts through AJAX. This is not what you want to do if you want to download a file. Instead, you should open a new tab set to the URL of the file you wish to download.
Try this:
function clickedTest() {
window.open(myPath + "/Employee/GetExcel", "_blank");
}
If your browser still isn't initiating a download, but is instead just displaying a file, you may have to go one step further.
Somewhere in your server-side code, when you have access to the Response object, you should set the Content-Disposition header to attachment and provide a filename for the spreadsheet you are serving. This will inform your browser that the file you are requesting is meant to be downloaded, not displayed.
This can be done as follows:
Response.AddHeader("Content-Disposition", "attachment;filename=myfile.xls")
Of course, replace myfile.xls with the proper filename for your spreadsheet.

How can I force the browser/javascript to clear/ignore a cached file?

I have a Javascript program that extracts data from a text file (just a plain *.txt file) and then displays it in a table. It works as intended except for one issue: If I update the text file where the data lives in the update does not shows up on the table. The reason is that the file is being cached by the browser.
Is there a way to force Javascript to read from the latest version of the file and not from the cached version? Again, this is not a problem with the javascript file as doing Ctrl-5 and or Shift+Ctrl+R does not works and also updating the javascript file itself behaves as expected. it is only the file where the data is in that is the problem.
To read the text file I use the Webix toolkit which uses AJAX to read the file. The reading and parsing of the text file is done via Javascript and the Webix toolkit. There is very little html in my program.
//the name of the file is dependant of an user specified input
var theURL = rossObj.store_number.store_number + "macaddress.txt ";
webix.ajax(theURL,{
//response
error:function(text, xml, XmlHttpRequest){
webix.alert({ ok:"OK", type:"alert-warning", text:"could not open the following URL --> "+theURL, width:"400px"});
return "mac_address_error";
},
success:function(text, xml, XmlHttpRequest){
//parse the file;
}
});
Try adding a random number to the end of the url as a query string, the server will ignore but the browser will treat it as a new file
var theURL = rossObj.store_number.store_number +
"macaddress.txt?" +
Math.floor((Math.random() * 10000) + 1);

Issues in developing web scraper

I want to develop a platform where users can enter a URL and then my website will open the webpage in an iframe. Now the user can modify his website by simply right clicking and I will provide him options like "remove this element", "copy this element". I am almost through. Many of the websites are opening perfectly in iframe but for a few websites some errors have shown up. I could not identify the reason so asking for your help.
I have solved other issues like XSS problem.
Here is the procedure I have followed :-
Used JavaScript and sent the request to my Java server which makes connection to the URL specified by the user and fetches the HTML and then use Jsoup HTML parser to convert relative URLs into absolute URLs and then save the HTML to my disk in Java. And then I render the saved HTML into my iframe.
Is somewhere wrong ?
A few websites are working perfectly but a few are not.
For example:-
When I tried to open http://www.snapdeal.com it gave me the
Uncaught TypeError: Cannot read property 'paddingTop' of undefined
error. I don't understand why this is happening..
Update
I really wonder how this is implemented? # http://www.proxywebsites.in/browse.php?u=Oi8vd3d3LnNuYXBkZWFsLmNvbQ%3D%3D&b=13&f=norefer
2 issues, pick any you like:
your server side proxy code contains bugs
plenty of sites have either explicit frame-break code or at least expect to be top level frame.
You can try one more thing. In your proxy script you are saving your webpage on your disk and then loading into iframe. I think instead of loading the page you saved on disk in iframe try to open that page in browser. All those sites that restirct their page to be loaded into iframe will now get opened without any error.
Try this I think it an work
My Proxy Server side code :-
DateFormat df = new SimpleDateFormat("ddMMyyyyHHmmss");
String dirName = df.format(new Date());
String dirPath = "C:/apache-tomcat-7.0.23/webapps/offlineWeb/" + dirName;
String serverName = "http://localhost:8080/offlineWeb/" + dirName;
boolean directoryCreated = new File(dirPath).mkdir();
if (!directoryCreated)
log.error("Error in creating directory");
String html = Jsoup.connect(url.toString()).get().html();
doc = Jsoup.parse(html, url);
links = doc.select("link");
scripts = doc.select("script");
images = doc.select("img");
for (Element element : links) {
String linkHref = element.attr("abs:href");
if (linkHref != "") {
element.attr("href", linkHref);
}
}
for (Element element : scripts) {
String scriptSrc = element.attr("abs:src");
if (scriptSrc != "") {
element.attr("src", scriptSrc);
}
}
for (Element element : images) {
String imgSrc = element.attr("abs:src");
if (imgSrc != "") {
element.attr("src", imgSrc);
log.info(imgSrc);
}
}
And Now i am just returning the path where i saved my html file
That's it about my server code

Getting notified when the user clicks a link in an embedded PDF

I got a PDF embedded in my page, and I'd like to set something like a Javascript-callback to be called whenever the user clicks a link within the PDF.
Is there a way to accomplish this?
If you check out the Acrobat JS Reference for the minimum version you want to support, you'll see documentation on the HostContainer object.
In the PDF:
this.hostContainer.messageHandler =
{
onMessage: function(messageArray)
{
for(var i = 0; i < messageArray.length; i++)
console.println("Message " + i + ": " + messageArray[i]);
},
onError: function(error, messageArray){ },
onDisclose: function() {return true;}
};
In your HTML, assuming your PDF is inside an <object id="thePdf"> tag:
function messageFunc(messageArray) {
for(var i = 0; i < messageArray.length; i++)
alert("Message " + i + ": " + messageArray[i]);
}
document.getElementById("thePdf").messageHandler = { onMessage: messageFunc };
In your PDF, you'd also need to modify the links so they have a JS action that would post a message to the containing web page. This could be done programmatically (varying wildly depending on the language/library you use), or manually in Acrobat Pro.
this.hostContainer.postMessage(["urlClicked", "http://blah.blah.blah..."]);
Not terribly hard, but no one's ever heard of it. I'd be stunned if this worked anywhere outside an Adobe viewer (Reader/Acrobat) for the next several years.
If you want to send a message from your HTML to the PDF for some reason, it goes something like this:
var thePDF = document.getElementById("thePdf");
thePDF.postMessage(["This", "is", "an", "array", "too."]);
You could even yank out all the existing links and have the PDF request the links be opened by the wrapping HTML page... that way you can give the new windows names, close them from JS, etc. You can get down right snazzy.
But you have to be able to change the PDFs.
Your link is probably represented as a "Link annotation" inside your PDF file. Annotations in PDF can contain "Additional Actions", you could use a pdf processing software like iText (free for non commercial use) or Amyuni PDF Creator(commercial, usual disclaimer applis) to add a Javascript action to the "Additional Actions" collection of your link(s). You can invoke a page or method in your server using this Javascript code.
Client side:
PDF
$("#pdf-link").click(function(){
$.post('yoursite.com/phpfunctionpage/notifyPdf',
{event:'pdf'},
function(response){
alert(response['message']);
}, 'json'
);
});
Your server side:
function notifyPdf(){
$event = $_POST['event'];
if ($event == 'pdf'){
// handle notification here
echo json_encode(array('result'=>1, 'message'=>'notifiation successful'));
}
}
<a href="file.pdf" onclick:'javascriptFunction();'>Open the pdf file</a>
<script>
function javascriptFunction(){
}
</script>

Categories

Resources