We're currently using Alpaca Forms to generate forms which we use to edit data stored in json for our application. We're now looking for a way to, server side, generate PDF documents, using json-schema and the json.
Ideally this would be using C#, but frankly, we really could use any language, as long as we can put it behind a web service.
Basically, it would be Alpaca, but the output would be a PDF report, which could contain a cover page and other document friendly features. It would also use the "title" and "description" fields from the json-schema.
Any ideas other than trying to roll our own? I'd rather not PDF library, since most seem to not be that document oriented.
wkhtmltopdf is my personal favourite way of doing this. You should be able to convert your JSON schema into HTML, and then render it via that.
If you are using Node: You can use Chromium's (Opensource Chrome browser) Puppeteer to launch a headless browser, server side, which can generate a PDF.
const puppeteer = require('puppeteer');
const browser = await puppeteer.launch({headless: true});
const page = await browser.newPage();
page.setContent('<h1>My PDF!</h1>');
const myPdf = page.pdf();
See https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagepdfoptions for more PDF options when generating from Puppeteer
I haven't tested the code above but that's the basics of what I'm using to generate PDF's
npm i puppeteer will be needed :)
It may be difficult (impossible?) to convert the Alpaca Forms JSON automatically into something that lays out pages the way you want. For example, does the Alpaca JSON provide enough information to determine page size, orientation, headers, footers, numbering location and style etc?
Docmosis may be useful to you (please note I work for Docmosis). You would layout your PDF in a word processor document and call Docmosis to merge it with your JSON data to create the PDF. The fields in your template drive the data extraction so you can put <> into your template and the title will be extracted from the JSON. In the case of Alpaca it looks like the title might be keyed under "schema" in the JSON, so you would use <> in a Docmosis template. Page layout and styles come from the template. The quickest way to test this as a candidate solution is to create a cloud account, upload a template and call the REST API with your JSON to create the document. If that does what you need you have the cloud or on-premise options.
I hope that helps.
if ideally for you is C#, then to generate PDF from json you need:
Parse JSON to some C# collection;
Loop through collection and write data into PDF-table;
Save file as PDF.
For this purpose you will need some PDF-creating library.
Here is an example, how to implement it in C# using PDFFlow library:
Prepare class for storing data:
public sealed class ReportData
{
public string name { get; set; }
public string surname { get; set; }
public string address { get; set; }
}
Read data from JSON into collection:
string jsonFilePath = Path.Combine(SubfolderName, JSONFileName);
List<ReportData> jsonData = JsonSerializer.Deserialize<List<ReportData>>(File.ReadAllText(jsonFile));
Create PDF document and add table to it:
using Gehtsoft.PDFFlow.Builder;
var section = DocumentBuilder.New().AddSection();
var table = section.AddTable();
table
.AddColumnToTable("Name", 150)
.AddColumnToTable("Surname", 250)
.AddColumn("Address", 300);
Loop through collection and add data to a table:
foreach(var rowData in jsonData)
{
var row = table.AddRow();
row
.AddCellToRow(rowData.name)
.AddCellToRow(rowData.surname)
.AddCell(rowData.address);
}
Save document to PDF file:
section
.ToDocument()
.Build("Result.PDF");
To compile this code you need to add reference to PDFFlow library to your project.
Hope, this will help.
Here is a fully working example of PDF contract generation, demonstrating how to work with JSON as a data source: contract example
Related
I need to access REST service from .NET application and it seems it can be done with any of those two packages. It's not clear to me which package is supposed to be used in which scenarios. Can anyone bring more light into this?
The short answer is yes, use Microsoft.AspNet.WebApi.Client.
https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/
This package adds support for formatting and content negotiation to
System.Net.Http. It includes support for JSON, XML, and form URL
encoded data.
Microsoft.AspNet.WebApi.Client actually depends on Microsoft.Net.Http, and extends the HttpClient with some more features that you would likely need to talk to a RESTful service such as ASP.NET Web API (e.g. JSON and XML support).
Both packages operate in the System.Net.Http namespace and revolve around the key HttpClient class.
The Microsoft.AspNet.WebApi.Client package contains the System.Net.Http.Formatting.dll assembly, which adds some handy extension methods to HttpClient and HttpContent (and others).
So for example:
using (var client = new HttpClient())
{
var response = await client.GetAsync("http://localhost/foo/api/products/1");
response.EnsureSuccessStatusCode();
var product = await response.Content.ReadAsAsync<ProductInfo>();
}
The ReadAsAsync method is an extension method that Microsoft.AspNet.WebApi.Client adds onto the HttpContent object. This automatically figures out if the response is JSON, XML or form URL encoded (the aforementioned content negotiation), and then uses the corresponding formatter to de-serialize it into your strongly typed model (in this case, ProductInfo).
If you tried to just use Microsoft.Net.Http, the ReadAsAsync method wouldn't be available to you, and you'd only be able to read the content as raw data such as bytes or string, and have to do the serializing / de-serializing yourself.
You also get extension methods to PUT / POST back to the service in JSON or XML without having to do that yourself:
// Save the ProductInfo model back to the API service
await client.PutAsJsonAsync("http://localhost/foo/api/products/1", product);
Key Microsoft.AspNet.WebApi.Client extensions:
https://msdn.microsoft.com/en-US/library/system.net.http.httpclientextensions.aspx
https://msdn.microsoft.com/en-US/library/system.net.http.httpcontentextensions.aspx
I am trying to make a generic function that returns objects obtained via a REST API JSON response. I want to provide the type with a generic, have it submit the request/parse the JSON, and return a list of objects of the provided type (such as Item). I have the part of getting the JSON response, but using generics is new for me. Here's a pseudocode of the situation holding me up:
class Model {
func setPropertiesFromJSON(data: NSData) {
// Lookup property names of object and set from JSON fields.
}
}
class Item : Model {
var a
var b
}
class RestEndpoint {
func getModels<T>() -> [T] {
let data: NSData = ... // Submit GET request and receive JSON data.
var models = [T]()
for objectData in data {
// How to create newobj as T (subtype of Model), set its properties,
// and add it to models array?
// let newobj: T as? TrackminiModel = T()
// newobj.setPropertiesFromJSON(objectData)
// models.append(newobj)
}
return models
}
}
let restEndpoint = RestEndPoint()
var items: [Item] = restEndpoint.getModels<Item>()
The commented out code is very incorrect but that is the goal. Any thoughts on how to do this?
From your question it sound like what your are interested in is something that is a fairly common need. The ability to communicate with a backend server using a Restful API. You can continue down the path you seem to be heading an create a lot of code to accomplish this, and this answer will not provide much help in that direction.
However I would like to point you to two open source libraries, ObjectMapper, which I think addresses your question. Here is a brief description of ObjectMapper (from its github page).
ObjectMapper is a framework written in Swift that makes it easy for
you to convert your Model objects (Classes and Structs) to and from
JSON.
The second project is AlamofireObjectMapper which I think in the end might be exactly what you are looking for. Here is a brief description from that projects githup page.
An extension to Alamofire which automatically converts JSON response
data into swift objects using ObjectMapper.
All of this is built on top of Alamofire which handle all the details of communicating with Restful API's.
Again here is a brief description of Alamofire.
Alamofire is an HTTP networking library written in Swift.
Chainable Request / Response methods
URL / JSON / plist Parameter Encoding
Upload File / Data / Stream
Download using Request or Resume data
Authentication with NSURLCredential
HTTP Response Validation
Progress Closure & NSProgress
cURL Debug Output
Comprehensive Unit Test Coverage
Complete Documentation
You might feel like picking up other libraries to accomplish some task is "cheating" you out of an opportunity to learn how to do something yourself, but there are still plenty of challenges in making an app. Some would say not taking advantage of these open source libraries is "undifferentiated heavy lifting"
http://www.playframework.com/documentation/2.1.x/JavaTodoList
Using the above tutorial as a reference, I have created an application which sends data from the model to view via the Application controller.
I have managed to display the model(Tasks) as a high chart. The code is here.
public static Result format(){
return ok(views.html.frmt.render("Visualize it",Task.all()));
}
This goes to this view page.
http://ideone.com/ycz9ko
Currently, I use scala templating inside the javascript code itself. Refer to lines 9-14 and lines 20-24.This unelegant style of doing things is not really optimal.
I want to be able to accomplish the above using Json instead.
public static Result jsonIt(){
List<Task> tasks = Task.all();
return ok(Json.toJson(tasks));
}
My Qns are how to send the JSON objects to a view template.
And how to parse it into a Highcharts format. Is there some standard procedure to do this ? Or else I have to write my own method to do this ?
It'll great if someone can show me a code snippet. Also I would prefer a post not using Ajax. I would just want to know how to do this first.
I also found this stackoverflow post useful.how to parse json into highcharts. However, it didnt answer the part about converting from Play format to Highcharts format.
Thanks in advance
You don't need to pass a json object to your template, instead you might do an ajax call from your client side javascript (your template) and get json response that you could use futher in javascript code to build a chart. For example :
You have some path that is bind to your controller jsonIt() like so /chartsdata/json
then using jquery shorthand for ajax request:
var chart_data = $.get('/chartsdata/json', function(data) {
return data;
});
now you can use a chart_data that is an array of objects where each object represents a Task, in your further javascript code to build a chart.
Is it possible to obtain the source of a MediaWiki page programmatically? I'd like to write a function that does the following (in Java-like pseudocode):
public static String getWikiText(articleURL){
//return the source of the page as wiki markup
}
Send a HTTP request with action=raw. (You could use the API as well, but that is more complicated.)
I want to parse the response coming from the server in JSON format. I have done some googling but i can't find any library or jar kind of thing.
Everywhere there is provided open source code as zip file.
How can i achieve this? if there is no jar available for blackberry then how to use that open source code in my application??
There is an open source JSON for J2ME API on Mobile and Embedded Application Developers Project
Also you can download JSON ME (Zip file) at JSON.org not supported anymore. But you can get it from here.
I believe you can simply copy content of json project src folder to your Blackberry project src folder, refresh it in eclipse package explorer and build it.
See for details: Using JavaScript Object Notation (JSON) in Java ME for Data Interchange
I am developing a Blackberry client application and I confronted the same problem. I was searching for JSON way of parsing the response which I get from the server. I am using Eclipse plug-in for BB as IDE and it comes with BB SDK including the ones for JSON.
The easiest answer to this question is that:
Initially do not forget to use this import statement:
import org.json.me.JSONObject;
Then assign your JSON formatted response from the server to a String variable:
String jsonStr = "{\"team\":\"Bursaspor\",\"manager\":\"Ertuğrul Sağlam\",\"year\":\"2010\"}";
Create a JSONObject:
JSONObject obj = new JSONObject(jsonStr);
i.e. if you want to use the value of the "team" field which is "Bursaspor" then you should use your JSONObject like this:
obj.getString("team")
This call will return the string value which is "Bursaspor".
P.S: I inspired this solution from this site which simply explains the solution of the same problem for Android development.
http://trandroid.com/2010/05/17/android-ile-json-parse-etme-ornegi-1/
When you got response string then use this code
try {
JSONObject jsonres = new JSONObject(jsons);
System.out.println("Preview icon from jsonresp:"+jsonres.getString("mydata"));
} catch (JSONException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
one thing jsons is your response string which is in json format & mydata your key of data so you can get your data from JSONObject. Thnks
chek this post to find out how to get JSONME source from SVN:
http://www.java-n-me.com/2010/11/how-to-import-source-code-from-svn-to.html
Hope it helps someone.
You can also try :
http://pensivemode.fileave.com/verified_json.jar
I was also looking for a jar version of json (to link along my lib) :
https://radheshg.wordpress.com/tag/json/
but it seems not portable :
Building example
C:\Program Files (x86)\Research In Motion\BlackBerry JDE 4.5.0\bin\rapc.exe -quiet import="C:\Program Files (x86)\Research In Motion\BlackBerry JDE 4.5.0\lib\net_rim_api.jar";lib\${PROJECT}.jar;lib\json.jar codename=example\example example\example.rapc warnkey=0x52424200;0x52525400;0x52435200 Y:\src\${PROJECT}-java.git\example\src\mypackage\MyApp.java Y:\src\${PROJECT}-java.git\example\src\mypackage\MyScreen.java
tmp3139/org/json/me/JSONArray.class: Error!: Invalid class file: Incorrect classfile version
Error while building project
http://supportforums.blackberry.com/t5/Java-Development/JSON-library/m-p/573687#M117982
So far JSON.simple is looking like a great viable option.
JSONParser parser=new JSONParser();
System.out.println("=======decode=======");
String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
Object obj=parser.parse(s);
JSONArray array=(JSONArray)obj;
System.out.println("======the 2nd element of array======");
System.out.println(array.get(1));
System.out.println();