How to create PDF Documents in Node.JS.? Is there any better solution to manage templates for different types of PDF creation.
I am using PDFKit to create PDF Documents and this will be server side using Javascript. I can not use HTML to create PDF. It will blob of paragraphs and sections with replacing tags with in.
Does anyone know Node.js has any npm package that can deal templates with paragraphs sections headers.
Something like
getTemplateByID() returns a template that contains sections , headers, paragraphs and then i use to replace appropriate tags within the template.
In my case, I have to get my HTML template from my database (PostgreSQL) stocked as stream. I request the db to get my template and I create a tmp file.
Inside my template, I have AngularJS tags so I compile this template with datas thanks to the 'ng-node-compile' module:
var ngCompile = require('ng-node-compile');
var ngEnvironment = new ngCompile();
var templateHTML = getTemplateById(id);
templateHTML = ngEnvironment.$compile(templateHTML)(datas);
Now I have my compiled template (where you can set your paragraph etc.) and I convert them into PDF thanks to a PhantomJS module 'phantom-html-to-pdf'
var phantomHTML2PDF = require('phantom-html-to-pdf')(options);
phantomHTML2PDF(convertOptions, function (error, pdf) {
if(error) console.log(error);
// Here you have 'pdf.stream.path' which is your tmp PDF file
callback(pdf);
});
Now you have your compiled and converted template (pdf), you can do whatever you want ! :)
Useful links:
https://github.com/MoLow/ng-node-compile
https://github.com/pofider/phantom-html-to-pdf
I hope this help !
Related
I would like to use a nunjucks render as my HTML for a window in my electron app but I can't find a way, is it possible? From what I have seen there are 2 ways to load HTML in window:
// Load a remote URL
win.loadURL('https://github.com')
// Or load a local HTML file
win.loadURL(`file://${__dirname}/app/index.html`)
And when I render my nunjucks template I have a string stored in a javascript variable:
render = nunjucks.render('./template/Template.html', data);
How can I use that string as an html for my window?
Many thanks everyone
You can pack your HTML into a data URI and pass that to win.loadURL:
const html = "<html><body><h1>Hello, world!</h1></body></html>";
win.loadURL("data:text/html;charset=utf-8," + encodeURI(html));
With your nunjucks render:
const render = nunjucks.render('./template/Template.html', data);
win.loadURL("data:text/html;charset=utf-8," + encodeURI(render));
I'd like to use JSON2HTML to parse the HTML data from JSON and render it in an UIWebView (using Swift 3.0). Please let me know how to achieve it. Thanks in advance!
Here's what I've tried:
let jsfile1 = try!String(contentsOfFile: Bundle.main.path(forResource: "json2html", ofType: "js")!)
func loadJS()
{
var getData={}
var context = JSContext()
var valSwiftyJson:JSON = [:]
var test = context?.evaluateScript(jsfile1)
let testFunction = test?.objectForKeyedSubscript("json2html")
let urlString = //Have removed the URL string due to restrictions
Alamofire.request(urlString,encoding:JSONEncoding.default).responseJSON
{ response in
if let alamoJson = response.result.value
{
let swiftyJson = JSON(data:response.data!)
valSwiftyJson = swiftyJson["FormInfo"]["Form"]
print(valSwiftyJson)
}
}
let result = testFunction?.call(withArguments: [getData,valSwiftyJson])
webView.loadHTMLString((result?.toString())!, baseURL: nil)
}
Finally, I managed to solve the issue by creating an index.html file (locally stored) and I referred the JSON2HTML library inside it. I then added the JSON(HTML inside) content dynamically to it each time whenever I needed to convert JSON to HTML. At last I load the final index.html in the UIWebView (it worked like charm).
Are you talking about this library as JSON2HTML ? If so, I don't think there is a library for translating the JSON elements to HTML in Swift.
Do you plan to download the JSON elements from a back-end ? Then, as there is a node.js wrapper to JSON2HTML, I would recommend to do the translating from JSON to HTML on the same server. Thus you would just download the HTML compiled data and rendering it in the UIWebView would be as easy as this line of code (in Swift 3) :
// html is the HTML data downloaded from your back-end
webView.mainFrame.loadHTMLString(html, baseURL: nil)
I am using local files to feed the templates for an Apple TV project. When I pass the Base URL of where my files reside, and then push the template, embedded image links work fine.
But when I create a template on the fly (as a string), and try to push that, the Base URL is not being read, and I get image links like this:
<heroImg src="${this.BASEURL}myImage.png"></heroImg>
Here is the javascript function that reads the string I create:
function myJSFunction (incomingString) {
if (incomingString) {
Presenter.showLoadingIndicator("defaultPresenter");
var doc = Presenter.makeDocument(incomingString);
Presenter.defaultPresenter.call(Presenter, doc);
}
}
And the strings I am creating don't contain javascript, i.e. they don't start like this:
var Template = function() { return `<?xml version="1.0" encoding="UTF-8" ?>
etc
I know I could write the full Base URL into the image links, but is there any way of keeping the ${this.BASEURL} in the paths I create?
I'm currently working on a small project in which I want to convert couple (or more) Markdown files into HTML and then append them to the main document. I want all this to take place client-side. I have chose couple of plugins such as Showdown (Markdown to HTML converter), jQuery (overall DOM manipulation), and Underscore (for simple templating if necessary). I'm stuck where I can't seem to convert a file into HTML (into a string which has HTML in it).
Converting Markdown into HTML is simple enough:
var converter = new Showdown.converter();
converter.makeHtml('#hello markdown!');
I'm not sure how to fetch (download) a file into the code (string?).
How do I fetch a file from a URL (that URL is a Markdown file), pass it through Showdown and then get a HTML string? I'm only using JavaScript by the way.
You can get an external file and parse it to a string with ajax. The jQuery way is cleaner, but a vanilla JS version might look something like this:
var mdFile = new XMLHttpRequest();
mdFile.open("GET", "http://mypath/myFile.md", true);
mdFile.onreadystatechange = function(){
// Makes sure the document exists and is ready to parse.
if (mdFile.readyState === 4 && mdFile.status === 200)
{
var mdText = mdFile.responseText;
var converter = new showdown.Converter();
converter.makeHtml(mdText);
//Do whatever you want to do with the HTML text
}
}
jQuery Method:
$.ajax({
url: "info.md",
context: document.body,
success: function(mdText){
//where text will be the text returned by the ajax call
var converter = new showdown.Converter();
var htmlText = converter.makeHtml(mdText);
$(".outputDiv").append(htmlText); //append this to a div with class outputDiv
}
});
Note: This assumes the files you want to parse are on your own server. If the files are on the client (IE user files) you'll need to take a different approach
Update
The above methods will work if the files you want are on the same server as you. If they are NOT then you will have to look into CORS if you control the remote server, and a server side solution if you do not. This question provides some relevant background on cross-domain requests.
Once you have the HTML string, you can append to the whatever DOM element you wish, by simply calling:
var myElement = document.getElementById('myElement');
myElement.innerHTML += markdownHTML;
...where markdownHTML is the html gotten back from makeHTML.
I have to create a module in a specific project, which already uses PrototypeJS.
What I have:
- An XML File with information
What I want:
- A simple div, which displays the (with XPath filterd) Content of the XML-File.
I am complete new to PrototypeJS and dont know where to begin, so I appreciate your help.
Blessing
chris
If by "local" you mean "client-side", you will have to :
include a file input for the user to upload the xml file to your server
fetch the xml file by ajax (easiest way) to have it as an xml document in your javascript
parse the xml file with the dedicated API
build an HTML representation of the content using text, images, etc. and include it in your div.
edit: to clarify the fetch part, here is how you can do it using Prototype:
new Ajax.Request('myfile.xml', {
onSuccess: function(transport) {
myParseXml(transport.responseXML);
},
onFailure: function(transport) {
alert('Failure! Status code '+transport.status+' ('+transport.statusText+')');
}
);
function myParseXml(xmlDoc) {
var root = xmlDoc.documentElement;
...
}
Try:
<xml src="MyData.xml" id="mydata" >
var mydata = document.getElementById('mydata');