Can PDFreactor be used to create PDF documents from browser DOM? - pdf-reactor

Can PDFreactor be used as a Web Service whereby javascript running on a browser can use the REST API to shuttle page content from the DOM to be converted to PDF? In this application, the content being rendered in the browser is generated exclusively by browser-side javascript (using the D3 library); the requirement here is to provide an "Export to PDF" type action to the browser end-user from the currently rendered page contents (via a button or menu action). The goal would then be to shuttle elements from the current DOM to PDFreactor via the REST API so that the Web Service could generate the PDF. Is this a reasonable use of PDFreactor?
Thank you in advance.

It is of course possible to convert the HTML content which was already processed by the browser with PDFreactor. In this case you could e.g. use the JavaScript API to pass the content extracted from the "body" element to PDFreactor and display the resulting PDF in the same page. Please see an example script below:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://www.pdfreactor.com/product/wrappers/javascript/lib/PDFreactor.js"></script>
<script>
window.onload = function() {
convertToPDF();
}
function convertToPDF() {
// Create new PDFreactor instance
var pdfReactor = new PDFreactor();
// Get the content from the body element
var content = "<html><body>"+document.body.innerHTML+"</body></html>";
// Create a new PDFreactor configuration object
var config = {
// Specify the input document
'document': content,
// Set a base URL for images, style sheets, links
baseURL: window.location.href,
}
// Render document and save result
pdfReactor.convert(config, function(result) {
document.body.innerHTML += '<iframe id="result" style="width: 100%; height: 95vh"></iframe>';
document.getElementById("result").src = "data:application/pdf;base64," + result.document;
}, function(error) {
document.body.innerHTML += "<h1>An Error Has Occurred</h1>"
+ "<h2>" + error + "</h2>";
});
}
</script>
</head>
<body>
<p>Hello World</p>
</body>
</html>
However as PDFreactor supports a variety of popular JavaScript libraries including D3.js, jQuery, etc. it might be more efficient to directly pass your input document including the JavaScript to the PDFreactor Web Service instead of converting the HTML rendered by the browser. PDFreactor will process any JavaScript within your input document, as long as JavaScript processing (disabled by default) is enabled in your PDFreactor integration.

Related

Display external application forms within Microsoft Dynamics 365

We have our own system which we need to integrate with MS Dynamics 365.For Example : In Accounts section we need to add an extra tab that loads IFrame or something that retrieves some extra information from our system.
The following are the things that I reached :
Inserting IFrame within a new Dashboard: (but it will not fetch specific account information, it will only pass the currently logged in user along with the organization name)
Unified Service Desk (USD): (we may add customization but this is a desktop app and we need it to be on web)
Microsoft flow: this would only work in the background when you create or edit an account (not sure if it has another functionality)
Extensions: Not sure how to use it to achieve the same functionality, I believe the solution may be here but I just need from where to start.
Has anybody done a similar thing before?
Thank you
You can definitely do it,
Here is how I just tried on one of my Trail Instance.
I added new Tab as you need, I called it "HTML Page"
On this Tab I added Webresource, you can add Iframe as well and call your external WebPage.
For my simple use case I created a simple HTML page as webresource in CRM and configured it to Webresource tab as below
Sample code for HTML. Dont worry about long html file. Mostly it is bla bla. What is of our importance is <body onload="myFunction()"> and then in
<script>
function myFunction() {
debugger;
alert("Account Id when from fromcontext is ");
alert(parent.Xrm.getformContext().data.entity.getId());
}
</script>
complete HTML code below
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>My first styled page</title>
</head>
<body onload="myFunction()">
<!-- Site navigation menu -->
<ul class="navbar">
<li>Home page
<li>Musings
<li>My town
<li>Links
</ul>
<!-- Main content -->
<h1>My first styled page</h1>
<p>Welcome to my styled page!
<p>It lacks images, but at least it has style.
And it has links, even if they don't go
anywhere…
<p>There should be more here, but I don't know
what yet.
<!-- Sign and date the page, it's only polite! -->
<address>Made 5 April 2004<br>
by myself.</address>
<script>
function myFunction() {
debugger;
alert("Account Id when from fromcontext is ", parent.Xrm.getformContext().data.entity.getId());
}
</script>
</body>
</html>
Also on Form Load of account I added additional Javascript. This javascript will create global variable which could be called from your webresource.
Article Link for additional Javascript
Sample code used for Javascript below
formContext=null;
function onload(executionContext){
debugger;
var formContext = executionContext.getFormContext();
Xrm.getformContext = function (){
return formContext;
};
Xrm.getParentAttribute = function (attrName) {
debugger;
return formContext.getAttribute(attrName);
};
Xrm.getParentControl = function (attrName) {
debugger;
return formContext.getControl(attrName);
};
}
Final Result will be something like below
Summary:
Create Wberesource/Iframe
Create Additiona Js on Load
Use global variable in your webresource.

Google App Script and Html Form not communicating

I need help with Google App Script on a Google Sheet and an Html form. I just cannot get them to connect properly. The form has a text box and two buttons. The user enters a name in the text box and press the start button. The start button records time to a variable. When finished, the user presses finish. The finish button records the time and processes the text box and start button. This info is sent back to the Google App Script to be written to the Sheet. I would like to use an AJAX or JQuery call, but it doesn't seem to be working. Need a little help getting the nice form working. I have tried doGet(e) and doGet() functions, but those aren't working. I have tried lots of different versions of the code. This isn't my final html form, but it has the same point. If I click the button, AJAX should return something to the Google App Script after processing. New to Google App Scripting and need help. Thanks!
code.gs
function doGet(e) {
var result = "";
try {
result = "Hi" + e.queryString;
//should write to the spreadsheet the information here
} catch (f) {
result= "Error" + f.toString();
}
result=JSON.stringify({"result":result});
return ContentService
.createTextOutput( "(" + result + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
//where does HtmlService.createHtmlOutput('index.html') go?
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
// Make an AJAX call to Google Script
function callGoogleScript() {
var url = "https://script.google.com/macros/s/" my script id "/exec";
var data = { name: "Tom", city: "Nowhere" };
var request = jQuery.ajax({
url:url+encodeURIComponent(data),
method: "GET",
dataType: "jsonp"
});
}
// print the returned data
function ctrlq(e) {
console.log(e.result)
}
</script>
</head>
<body>
<button id="test" name="test" onclick="callGoogleScript()">Test</script>
</body>
</html>
Edit: This is for a Web App.

Using MVC3, how to get browsers to explicitly interpret a transferred script as HTML?

In my MVC app, I am returning some Javascript. Howveer, I am using the anti-forgery token on the view, so the rendered result would be
<input name="__RequestVerificationToken" type="hidden" value="E8as+4Ff1u/c/+kuFcNXXCREB5pz5GAfH2krN5RvzURJaHZSApuRc4czZqmoITaKdy0XhN5sFfRzl4ne+wB3PkWOscBWzoIxUk3hGaFwDxRXSbMs8K9IwojEAtV5u57MR7hiSujr6MOTpjjbf5FPaYgO4gmH6lSR9mbSyO2IedI=" />
<script type="text/javascript">
// Here, we ensure that jQuery is loaded then load up the rest of our JS in in order.
ord = Math.random() * 10000000000000000;
...
So there is some HTML to be added to the page then the JS.
The issue is that I get the following notification in Chrome:
Resource interpreted as Script but transferred with MIME type
I need the browser to interpret this as HTML in order to make use of the anti-forgery token.
I have tried putting this on the view:
<%#Page Title="" Language="C#" ContentType="text/xml" %>
Which renders:
<%System.Web.WebPages.DynamicPageDataDictionary`1[System.Object] Title="" Language="C#" ContentType="text/xml" %>
<input name="__RequestVerificationToken" type="hidden"
...
...but the same message persists.
In my controller I have also tried:
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(page.clientScript);
return new ContentResult
{
ContentType = "text/xml", // also tried text/html
Content = Encoding.UTF8.GetString(bytes),
ContentEncoding = System.Text.Encoding.UTF8
};
Same issue.
-- UPDATE --
This is how I'm invoking the MVC app to return the text:
// used to load scripts on to the client script using a non-blocking asynch request
(function() {
function async_load(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://myserver/MyAppPath/someids';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
}
if (window.attachEvent)
window.attachEvent('onload', async_load);
else
window.addEventListener('load', async_load, false);
})();
If I've understood correctly, you need an MVC action which returns both html and a script tag that can be injected in a page via a <script... include. You also want to render this via an MVC view.
The biggest issue you've missed is that in order to get this content into the calling page, you need to execute document.write from the script - you can't just send back HTML and script in response to the script include - the browser won't understand it, it's expecting javascript only.
There are a few ways to do this - I have written a full suite of ViewContent MVC controller methods, with the same overloads as View which returns the result of a view to a controller action as a string. I can then pass that back as a string literal (useful for html email generation) but also to a javascript encoder.
In this case, you don't need to be so generalist. We can leverage Darin Dimitrov's answer to this SO: Embed MVC Partial View into a document.write JS call and split your view into a View and a partial. The view writes the document.write() skeleton, and the partial view renders the dynamic html you want to be injected into the page. It's unclear if you're using the Anti Forgery Token in the main view which will call the script (in which case it should be rendered as part of the view that it returns) or if you're actually hard-coding it in the script. The second should definitely not be used but I'm writing this answer as if it is, because that appears to be what you want.
First, your partial view (let's call it Fragment.cshtml, put it in ~/Views/Shared)
<input name="__RequestVerificationToken"
type="hidden"value="[ommitted]" />
<script type="text/javascript">
// Here, we ensure that jQuery is loaded then load up the rest of our JS in in order.
ord = Math.random() * 10000000000000000;
...
Second, the host view, called SomeIds.cshtml
#{ Response.ContentType = "text/javascript"; }
document.write('#Html.Raw(HttpUtility.JavaScriptStringEncode(Html.Partial("~/Views/Shared/Fragment").ToHtmlString()))')
Now this view returns a document.write call that injects the HTML returned by the Fragment.cshtml into the page that includes the script.
Are you returning a PartialView that has all of the markup rendered?
Create a PartialView with your (form and script includes) and in your Controller:
public ActionResult Index(Models.MyModel model)
{
// validate the model if needed
return PartialView("[My PartialView Name]", model);
}
You could put your scripts in separate files, and add the [script src] tags in the PartialView.

Using Jquery in Controller Page-ASP.NET MVC-3

Could any one give an example, how to use Jquery in Controller Page. MVC3 -ASP.NET(How To put various tags like )
I want to show a simple alert before rendering a view in Controller.
Thank you.
Hari Gillala
Normally scripts are part of the views. Controllers shouldn't be tied to javascript. So inside a view you use the <script> tag where you put javascript. So for example if you wanted to show an alert just before rendering a view you could put the following in the <head> section of this view:
<script type="text/javascript">
alert('simple alert');
</script>
As far as jQuery is concerned, it usually is used to manipulate the DOM so you would wrap all DOM manipulation functions in a document.ready (unless you include this script tag at the end, just before closing the <body>):
<script type="text/javascript">
$(function() {
// ... put your jQuery code here
});
</script>
If you are talking about rendering partial views with AJAX that's another matter. You could have a link on some page that is pointing to a controller action:
#Html.ActionLink("click me", "someAction", null, new { id = "mylink" })
and a div container somewhere on the page:
<div id="result"></div>
Now you could unobtrusively AJAXify this link and inject the resulting HTML into the div:
$(function() {
$('#mylink').click(function() {
$('#result').load(this.href, function() {
alert('AJAX request finished => displaying results in the div');
});
return false;
});
});

Partial page refresh for evary X seconds with Jquery and Ajax?

1) I have to change images dynamically according to values for every x seconds.
I'm using the following function:
setInterval(function() {
$("#content").load(location.href+" #content>*","");
}, 5000);
It works fine for updating the value, but the images not getting updated into its position.
2) From the 1st question i want to know whether the jquery and css files included in the head tag will load every x seconds or not. if not how to load?
Please give me the suggestion.
If you are returning a whole HTML page and returning it into the body of another page, that is a bad idea.
Think about it, your html structure would be something like
<doc type>
<html>
<head>
</head>
<body>
<div>
<doc type>
<html>
<head>
</head>
<body>
<div>
</div>
</body>
</html>
</div>
</body>
</html>
Ideally you should be retuning just the content that is to be displayed, not everything.
If you are just updating images, there usually is no need to make an XHR call. You can just set the image src and force the browser to update that content that way.
Does this need to be done with Ajax at all? How many images are you going to cycle through? If it is only a few, just keep all of the src's on the page and switch the image src attribute periodically. This requires no page reload. You may also want to preload all the images so there is no flicker when changing to the other image. For example:
$(function () {
var images = ['1.png', '2.png', '3.png'];
$.each(images, function (index, src) {
$("<img />").attr('src', src); //preload
});
var keep = 1;
setInterval(function () {
$("#main_img").attr('src', images[keep]);
keep++;
if (keep >= images.length) { keep = 0; }
}, 5000);
});
Now if you don't want to hard code the image urls in the JS, you can load them initially with a single Ajax request.
I would only recommend using Ajax to do all the work if you are talking about an unpredictable set of images or some massive number of images.

Resources