Code Monkey home page Code Monkey logo

json-to-pdf's Introduction

json-to-pdf

This project aims to provide a way to declaratively generate PDF reports using JSON notation via the clj-pdf library.

An example document can be viewed here.

Installation

Gradle

repositories {
    jcenter()
    maven {
        url 'http://clojars.org/repo'
    }
}

compile "json-to-pdf:json-to-pdf:0.8.3"

Maven

json-to-pdf is available from the Clojars repo:

<repositories>
<repository>
  <id>clojars.org</id>
  <url>http://clojars.org/repo</url>
</repository>
</repositories>

<dependency>
  <groupId>json-to-pdf</groupId>
  <artifactId>json-to-pdf</artifactId>
  <version>0.8.3</version>
</dependency>

see here for a complete sample project

Usage

JSON documents are represented by an array containing one or more elements. The first element in the document must be a map containing the metadata.

import cljpdf.text.BadElementException;
import cljpdf.text.Document;
import cljpdf.text.Image;
import cljpdf.text.pdf.PdfWriter;
import org.yogthos.JsonPDF;
import cljpdf.text.pdf.PdfPageEventHelper;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;

public class Main {
    public static void main(String[] args) throws Exception {
        String jsonDoc1 = "[{}, [\"paragraph\", \"hello world\"]]";
        String jsonDoc2 = "[{\"pages\":true,\"orientation\":\"landscape\"}, [\"paragraph\", \"hello world\"]]";

        JsonPDF.writeToFile(jsonDoc1, "out.pdf", null);

        java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
        JsonPDF.writeToStream(new ByteArrayInputStream(jsonDoc1.getBytes()),
                new FileOutputStream("outstream.pdf"), null);

        System.out.println(new File(".").getAbsolutePath());
        JsonPDF.writeToFile(jsonDoc1, "out.pdf", new HeaderFooter("resources/mandelbrot.jpg"));
    }

    static class HeaderFooter extends PdfPageEventHelper {
        private Image img;
        public HeaderFooter(String imagePath)
                throws BadElementException, MalformedURLException, IOException {
            ClassLoader classLoader = getClass().getClassLoader();
            File file = new File(imagePath);
            this.img = Image.getInstance(file.getPath());
            this.img.scaleToFit(100, 100);
            this.img.setAbsolutePosition(25,700);
        }

        @Override
        public void onStartPage(PdfWriter writer, Document document) {
            try {
                writer.getDirectContent().addImage(this.img);
            } catch (Exception x) {
                x.printStackTrace();
            }
        }
    }
}

Document Format

Metadata

All fields in the metadata section are optional:

{"right-margin":10,
 "subject":"Some subject",
 "creator":"Jane Doe",
 "doc-header":["inspired by", "William Shakespeare"],
 "bottom-margin":25,
 "pages":true,
 "author":"John Doe",
 "header":"Page header text appears on each page",
 "left-margin":10,
 "title":"Test doc",
 "size":"a4",
 "letterhead":["A simple Letter head"],
 "orientation":"landscape",
 "font":{"size":11},
 "footer":
 "Page footer text appears on each page (includes page number)",
 "top-margin":20}

available page sizes:

"a0"
"a1"
"a10"
"a2"
"a3"
"a4"
"a5"
"a6"
"a7"
"a8"
"a9"
"arch-a"
"arch-b"
"arch-c"
"arch-d"
"arch-e"
"b0"
"b1"
"b10"
"b2"
"b3"
"b4"
"b5"
"b6"
"b7"
"b8"
"b9"
"crown-octavo"
"crown-quarto"
"demy-octavo"
"demy-quarto"
"executive"
"flsa"
"flse"
"halfletter"
"id-1"
"id-2"
"id-3"
"large-crown-octavo"
"large-crown-quarto"
"ledger"
"legal"
"letter"
"note"
"penguin-large-paperback"
"penguin-small-paperback"
"postcard"
"royal-octavo"
"royal-quarto"
"small-paperback"
"tabloid"

The font defaults to A4 page size if none provided and the orientation defaults to portrait, unless "landscape" is specified.

Font

A font is defined by a map consisting of the following parameters, all parameters are optional

  • "family": has following options: "courier":, "helvetica":, "times-roman":, "symbol":, "zapfdingbats": defaults to "helvetica":
  • "size": is a number default is 11
  • "style": has following options: "bold":, "italic":, "bold-italic":, "normal":, "strikethru":, "underline": defaults to "normal":
  • "color": is a vector of [r g b] defaults to black

example font:

{"style":"bold", "size":18, "family":"helvetica", "color":[0, 234, 123]}

note: Font styles are additive, for example setting style "italic": on the phrase, and then size 20 on a chunk inside the phrase, will result with the chunk having italic font of size 20. Inner elements can override style set by their parents.

Document sections

Each document section is represented by a vector starting with a keyword identifying the section followed by an optional map of metadata and the contents of the section.

Anchor

tag "anchor":

optional metadata:

  • "style": font
  • "leading": number

content:

iText idiosynchorsies:

  • when both font style and leading number are specified the content must be a string
  • when leading number is specified content can be a chunk or a string
  • when only font style is specified content must be a string
  • if no font style or leading is specified then content can be a chunk, a phrase, or a string
["anchor", {"style":{"size":15}, "leading":20}, "some anchor"]

["anchor", ["phrase", {"style":"bold"}, "some anchor phrase"]]

["anchor", "plain anchor"]

Chapter

tag "chapter":

optional metadata:

  • none

content:

  • string
  • paragraph
["chapter", "First Chapter"]

["chapter", ["paragraph", "Second Chapter"]]

Chunk

tag "chunk":

optional metadata:

  • "sub": boolean sets chunk to subscript
  • "super": boolean sets chunk to superscript

font metadata (refer to Font section for details)

  • "family":
  • "size":
  • "style":
  • "color":
["chunk", {"style":"bold"}, "small chunk of text"]

["chunk", {"super":true}, "5"]

["chunk", {"sub":true}, "2"]

Heading

tag "heading":

optional metadata:

  • "style": custom font for the heading
  • "align": specifies alignement of heading possible valuse "left":, "center":, "right":
["heading", "Lorem Ipsum"]

["heading", {"style": {"size":15}}, "Lorem Ipsum"]

["heading", {"style": {"size":10, "color":[100, 40, 150], "align":"right"}}, "Foo"]

Image

tag "image":

image data can be a base64 string, a string representing URL or a path to file, images larger than the page margins will automatically be scaled to fit.

optional metadata:

  • "scale": number - percentage relative to page size
  • "xscale": number - percentage relative to page size
  • "yscale": num - percentage relative to page size
  • "width": num - set width for image: overrides scaling
  • "height": num - set height for image: overrides scaling
  • "align": "left":, "center":, "right":
  • "annotation": ["title" "text"]
  • "pad-left": number
  • "pad-right": number
  • "base64": boolean - if set the image is expected to be a Base64 string
["image",
 {"xscale":0.5,
  "yscale":0.8,
  "align":"center",
  "annotation":["FOO", "BAR"],
  "pad-left":100,
  "pad-right":50}, ["read", "mandelbrot.jpg"]]

["image", "test/mandelbrot.jpg"]

["image", "http://clojure.org/space/showimage/clojure-icon.gif"]

Line

tag "line":

optional metadata:

  • "dotted": boolean
  • "gap": number ;space between dots if line is dotted

creates a horizontal line

["line"]

["line", {"dotted":true}]

["line", {"dotted":true, "gap":10}]

List

tag "list":

optional metadata:

  • "numbered": boolean
  • "lettered": boolean
  • "roman": boolean
  • "greek": boolean
  • "dingbats": boolean
  • "dingbats-char-num": boolean
  • "dingbatsnumber": boolean
  • "dingbatsnumber-type": boolean
  • "symbol" string (custom item prefix)

content:

  • strings, phrases, or chunks
["list", {"roman":true}, ["chunk", {"style":"bold"}, "a bold item"],
 "another item", "yet another item"]

Paragraph

tag "paragraph":

optional metadata:

  • "indent": number
  • "keep-together": boolean
  • "leading": number
  • "align": "left":, "center":, "right":

font metadata (refer to Font section for details)

  • "family":
  • "size":
  • "style":
  • "color":

content:

  • one or more elements (string, chunk, phrase, paragraph)
["paragraph", "a fine paragraph"]

["paragraph", {"keep-together":true, "indent":20}, "a fine paragraph"]

["paragraph",
 {"style":"bold",
  "size":10,
  "family":"halvetica",
  "color":[0, 255, 221]},
 "Lorem ipsum dolor sit amet, consectetur adipiscing elit."]

"font"

["paragraph", {"indent":50, "color":[0, 255, 221]},
 ["phrase", {"style":"bold", "size":18, "family":"halvetica"},
  "Hello Clojure!"]]

["paragraph", "256", ["chunk", {"super":true}, "5"], " or 128",
 ["chunk", {"sub":true}, "2"]]

Phrase

tag "phrase":

optional metadata:

  • "leading": number

font metadata (refer to Font section for details)

  • "family":
  • "size":
  • "style":
  • "color":

content:

  • strings and chunks
["phrase", "some text here"]

["phrase",
 {"style":"bold",
  "size":18,
  "family":"halvetica",
  "color":[0, 255, 221]}, "Hello Clojure!"]

["phrase", ["chunk", {"style":"italic"}, "chunk one"],
 ["chunk", {"size":20}, "Big text"], "some other text"]

["phrase", "styles" : ["italic", "underline"]]

Section

tag "section":

Chapter has to be the root element for any sections. Subsequently sections can only be parented under chapters and other sections, a section must contain a title followed by the content

optional metadata:

  • "indent": number
["chapter", ["paragraph", {"color":[250, 0, 0]}, "Chapter"],
 ["section", "Section Title", "Some content"],
 ["section", ["paragraph", {"size":10}, "Section Title"],
  ["paragraph", "Some content"], ["paragraph", "Some more content"],
  ["section", {"color":[100, 200, 50]},
   ["paragraph", "Nested Section Title"],
   ["paragraph", "nested section content"]]]]

Spacer

tag "spacer":

creates a number of new lines equal to the number passed in (1 space is default)

["spacer"]

["spacer", 5]

String

A string will be automatically converted to a paragraph

"this text will be treated as a paragraph"

Subscript

tag "subscript":

optional metadata:

  • "style": font

creates a text chunk in subscript

["subscript", "some subscript text"]

["subscript", {"style":"bold"}, "some bold subscript text"]

Superscript

tag "superscript":

optional metadata:

  • "style": font

creates a text chunk in subscript

["superscript", "some superscript text"]

["superscript", {"style":"bold"}, "some bold superscript text"]

Table

tag "table":

metadata:

  • "align": table alignment on the page can be: "left":, "center":, "right":
  • "background-color": [r g b] (int values)
  • "header": [{"backdrop-color": [r g b]} "column name" ...] if only a single column name is provided it will span all rows
  • "spacing": number
  • "padding": number
  • "border": boolean
  • "border-width": number
  • "cell-border": boolean
  • "width": number signifying the percentage of the page width that the table will take up
  • "widths": vector list of column widths in percentage
  • "header": is a vector of strings, which specify the headers for each column, can optionally start with metadata for setting header color
  • "offset": number
  • "num-cols": number
["table",
 {"header":["Row 1", "Row 2", "Row 3"],
  "width":50,
  "border":false,
  "cell-border":false},
 [["cell", {"colspan":2}, "Foo"], "Bar"], ["foo1", "bar1", "baz1"],
 ["foo2", "bar2", "baz2"]]

["table", {"border-width":10, "header":["Row 1", "Row 2", "Row 3"]},
 ["foo", "bar", "baz"], ["foo1", "bar1", "baz1"],
 ["foo2", "bar2", "baz2"]]

["table",
 {"border":false,
  "widths":[2, 1, 1],
  "header":[{"color":[100, 100, 100]}, "Singe Header"]},
 ["foo", "bar", "baz"], ["foo1", "bar1", "baz1"],
 ["foo2", "bar2", "baz2"]]

["table",
 {"cell-border":false,
  "header":[{"color":[100, 100, 100]}, "Row 1", "Row 2", "Row 3"],
  "cellSpacing":20,
  "header-color":[100, 100, 100]},
 ["foo",
  ["cell",
   ["phrase",
    {"style":"italic",
     "size":18,
     "family":"halvetica",
     "color":[200, 55, 221]},
    "Hello Clojure!"]],
  "baz"],
 ["foo1", ["cell", {"color":[100, 10, 200]}, "bar1"], "baz1"],
 ["foo2", "bar2", "baz2"]]

Table Cell

Cells can be optionally used inside tables to provide specific style for table elements

tag "cell":

metadata:

  • "color": [r g b] (int values)
  • "colspan": number
  • "rowspan": number
  • "border": boolean
  • "set-border": ["top": "bottom": "left": "right]": list of enabled borders, pass empty vector to disable all borders
  • "border-width": number
  • "border-width-bottom": number
  • "border-width-left": number
  • "border-width-right": number
  • "border-width-top": number

content:

Cell can contain any elements such as anchor, annotation, chunk, paragraph, or a phrase, which can each have their own style

note: Cells can contain other elements including tables

["cell", {"colspan":2}, "Foo"]

["cell", {"colspan":3, "rowspan":2}, "Foo"]

["cell",
 ["phrase",
  {"style":"italic",
   "size":18,
   "family":"halvetica",
   "color":[200, 55, 221]}, "Hello Clojure!"]]

["cell", {"color":[100, 10, 200]}, "bar1"]

["cell",
 ["table",
  ["Inner table Col1", "Inner table Col2", "Inner table Col3"]]]

Charting

tag "chart":

metadata:

  • "type": - bar-chart, line-chart, pie-chart
  • "x-label": - only used for line and bar charts
  • "y-label": - only used for line and bar charts
  • "time-series": - only used in line chart
  • "time-format": - can optionally be used with time-series to provide custom date formatting, defaults to "yyyy-MM-dd-HH:mm:ss"
  • "horizontal": - can be used with bar charts and line charts, not supported by time series
  • "background": - a vector of [r g b] integer values
  • "title": - the title of the chart

additional image metadata

  • "scale": number - percentage relative to page size
  • "width": num - set width for image: overrides scaling
  • "height": num - set height for image: overrides scaling
  • "align": "left|center|right"
  • "annotation": ["title" "text"]
  • "pad-left": number
  • "pad-right": number

bar chart

["chart",
 {"type":"bar-chart",
  "title":"Bar Chart",
  "background":[255,255,255],
  "x-label":"Items",
  "y-label":"Quality"}, [2, "Foo"], [4, "Bar"], [10, "Baz"]]

line chart

if "time-series": is set to true then items on x axis must be dates, the default format is "yyyy-MM-dd-HH"mm:ss"":, for custom formatting options refer here

["chart",
 {"type":"line-chart",
  "title":"Line Chart",
  "x-label":"checkpoints",
  "y-label":"units"},
 ["Foo", [1, 10], [2, 13], [3, 120], [4, 455], [5, 300], [6, 600]],
 ["Bar", [1, 13], [2, 33], [3, 320], [4, 155], [5, 200], [6, 300]]]
["chart",
 {"x-label":"time",
  "y-label":"progress",
  "time-series":true,
  "title":"Time Chart",
  "type":"line-chart"},
 ["Incidents", ["2011-01-03-11:20:11", 200],
  ["2011-02-11-22:25:01", 400], ["2011-04-02-09:35:10", 350],
  ["2011-07-06-12:20:07", 600]]]
["chart",
 {"type":"line-chart",
  "time-series":true,
  "time-format":"MM/yy",
  "title":"Time Chart",
  "x-label":"time",
  "y-label":"progress"},
 ["Occurances", ["01/11", 200], ["02/12", 400], ["05/12", 350],
  ["11/13", 600]]]

pie chart

["chart", {"type":"pie-chart", "title":"Big Pie"}, ["One", 21],
 ["Two", 23], ["Three", 345]]

A complete example

  [{"right-margin":50,
   "subject":"Some subject",
   "creator":"Jane Doe",
   "doc-header":["inspired by", "William Shakespeare"],
   "bottom-margin":25,
   "author":"John Doe",
   "header":"page header",
   "left-margin":10,
   "title":"Test doc",
   "size":"a4",
   "footer":"page",
   "top-margin":20},

   ["heading", "Lorem Ipsum"],

   ["paragraph", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec non iaculis lectus. Integer vel libero libero. Phasellus metus augue, consequat a viverra vel, fermentum convallis sem. Etiam venenatis laoreet quam, et adipiscing mi lobortis sit amet. Fusce eu velit vitae dolor vulputate imperdiet. Suspendisse dui risus, mollis ut tempor sed, dapibus a leo. Aenean nisi augue, placerat a cursus eu, convallis viverra urna. Nunc iaculis pharetra pretium. Suspendisse sit amet erat nisl, quis lacinia dolor. Integer mollis placerat metus in adipiscing. Fusce tincidunt sapien in quam vehicula tincidunt. Integer id ligula ante, interdum sodales enim. Suspendisse quis erat ut augue porta laoreet."],

   ["paragraph", "Sed pellentesque lacus vel sapien facilisis vehicula. Quisque non lectus lacus, at varius nibh. Integer porttitor porttitor gravida. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus accumsan ante tincidunt magna dictum vulputate. Maecenas suscipit commodo leo sed mattis. Morbi dictum molestie justo eu egestas. Praesent lacus est, euismod vitae consequat non, accumsan in justo. Nam rhoncus dapibus nunc vel dignissim."],

   ["paragraph", "Nulla id neque ac felis tempor pretium adipiscing ac tortor. Aenean ac metus sapien, at laoreet quam. Vivamus id dui eget neque mattis accumsan. Aliquam aliquam lacinia lorem ut dapibus. Fusce aliquam augue non libero viverra ut porta nisl mollis. Mauris in justo in nibh fermentum dapibus at ut erat. Maecenas vitae fermentum lectus. Nunc dolor nisl, commodo a pellentesque non, tincidunt id dolor. Nulla tellus neque, consectetur in scelerisque vitae, cursus vel urna. Phasellus ullamcorper ultrices nisi ac feugiat."],


   ["table",
   {"header":[{"color":[100, 100, 100]}, "FOO"], "cellSpacing":20},
   ["foo",
    ["cell",
     ["phrase",
      {"style":"italic",
       "size":18,
       "family":"halvetica",
       "color":[200, 55, 221]},
      "Hello Clojure!"]],
    "baz"],
   ["foo1", ["cell", {"color":[100, 10, 200]}, "bar1"], "baz1"],
   ["foo2", "bar2",
    ["cell",
     ["table",
      ["Inner table Col1", "Inner table Col2", "Inner table Col3"]]]]],

   ["paragraph", "Suspendisse consequat, mauris vel feugiat suscipit, turpis metus semper metus, et vulputate sem nisi a dolor. Duis egestas luctus elit eget dignissim. Vivamus elit elit, blandit id volutpat semper, luctus id eros. Duis scelerisque aliquam lorem, sed venenatis leo molestie ac. Vivamus diam arcu, sodales at molestie nec, pulvinar posuere est. Morbi a velit ante. Nulla odio leo, volutpat vitae eleifend nec, luctus ac risus. In hac habitasse platea dictumst. In posuere ultricies nulla, eu interdum erat rhoncus ac. Vivamus rutrum porta interdum. Nulla pulvinar dui quis velit varius tristique dignissim sem luctus. Aliquam ac velit enim. Sed sed nisi faucibus ipsum congue lacinia. Morbi id mi in lectus vehicula dictum vel sed metus. Sed commodo lorem non nisl vulputate elementum. Fusce nibh dui, auctor a rhoncus eu, rhoncus eu eros."],

   ["paragraph", "Nulla pretium ornare nisi at pulvinar. Praesent lorem diam, pulvinar nec scelerisque et, mattis vitae felis. Integer eu justo sem, non molestie nisl. Aenean interdum erat non nulla commodo pretium. Quisque egestas ullamcorper lacus id interdum. Ut scelerisque, odio ac mollis suscipit, libero turpis tempus nulla, placerat pretium tellus purus eu nunc. Donec nec nisi non sem vehicula posuere et eget sem. Aliquam pretium est eget lorem lacinia in commodo nisl laoreet. Curabitur porttitor dignissim eros, nec semper neque tempor non. Duis elit neque, sagittis vestibulum consequat ut, rhoncus sed dui."],


  ["anchor", {"style":{"size":15}, "leading":20}, "some anchor"],

  ["anchor", ["phrase", {"style":"bold"}, "some anchor phrase"]],

  ["anchor", "plain anchor"],

  ["chunk", {"style":"bold"}, "small chunk of text"],

  ["phrase", "some text here"],

  ["phrase",
   {"style":"italic",
    "size":18,
    "family":"halvetica",
    "color":[0, 255, 221]},
   "Hello Clojure!"],

   ["chapter", ["paragraph", "Second Chapter"]],

   ["paragraph", {"keep-together":true, "indent":20},
   "a fine paragraph"],

   ["list", {"roman":true}, ["chunk", {"style":"bold"}, "a bold item"],
   "another item", "yet another item"],

   ["chapter", "Charts"],

   ["chart",
   {"type":"bar-chart",
    "title":"Bar Chart",
    "x-label":"Items",
    "y-label":"Quality"},
   [2, "Foo"], [4, "Bar"], [10, "Baz"]],

   ["chart",
   {"type":"line-chart",
    "title":"Line Chart",
    "x-label":"checkpoints",
    "y-label":"units"},
   ["Foo", [1, 10], [2, 13], [3, 120], [4, 455], [5, 300], [6, 600]],
   ["Bar", [1, 13], [2, 33], [3, 320], [4, 155], [5, 200], [6, 300]]],

   ["chart", {"type":"pie-chart", "title":"Big Pie"}, ["One", 21],
   ["Two", 23], ["Three", 345]],

   ["chart",
   {"type":"line-chart",
    "time-series":true,
    "title":"Time Chart",
    "x-label":"time",
    "y-label":"progress"},
   ["Incidents", ["2011-01-03-11:20:11", 200],
    ["2011-01-03-11:25:11", 400], ["2011-01-03-11:35:11", 350],
    ["2011-01-03-12:20:11", 600]]]]

License


Distributed under LGPL, the same as clj-pdf.

json-to-pdf's People

Contributors

yogthos avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

json-to-pdf's Issues

Colspan broken?

Hello

i'm trying to create a table with colspan.
Here is the json:

[{},["table",{"header":["col1","col2","col3"]},[["cell",{"colspan":2},"Foo"],"YYY"]]]

i'm expecting a table with three columns and the second row should have a colspan over the first two fields and a third field.
But the result of this code is:
image
Any idea?

Cannot get gradle or maven to run after installing

For Maven
enviornment varibles
ev

maven powershell

For Gradle
This is weird now I'm getting this after installing Maven
`PS C:\Gradle> gradle -v

ERROR: JAVA_HOME is set to an invalid directory: C:\maven

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.
PS C:\Gradle> java -version
java version "10.0.1" 2018-04-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode)`

I also ran
iex (new-object net.webclient).downloadstring('https://get.scoop.sh') scoop install gradle
this in cmd not powershell
@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
But decided not to install it as I realized I just needed to run for gradle to be installed
scoop install gradle

I don't know if this is what I need to do to run gradle, but I ran
`❯ mkdir basic-demo
❯ cd basic-demo
❯ gradle init
Starting a Gradle Daemon (subsequent builds will be faster)

BUILD SUCCESSFUL in 3s
2 actionable tasks: 2 executed`
according to this tutorial

And that's where I got lost and confused and decided to try Maven instead. I think I would rather use Maven since it looks simpler, but after installing it both are not recognizing my Java directory. What do I do?

Image inside header.

Hello,

We've come up with the neccesity of inserting an image inside the header of the generated pdf using json-to-pdf.

We tried to tweak the json in order to achieve inserting the image, but as the documentation suggest, json-to-pdf seems to only accept plain text at the moment for the header element.

I saw there's an issue open since, 2016 with something reflecting almost the same neccesity on cli-pdf:

Was wondering if any progress was made in order to achieve that use-case, or if it's possible to modify existing json-to-pdf state to at least permitt the "hack" documented by @alemedeiros on the referenced issue.

Would be glad to help if any directions are given on how the change could be accomplished (even though I doesn't know clojure at all i would do my best).

Thanks in advance and thanks for the effort put on the library.

java.lang.NoClassDefFoundError: clojure.lang.Var

I was getting the same error than others trying to add the repository and library on gradle, so I tried to download the jar (json-to-pdf-0.7.5.jar), copy it to libs folder and add compile files('libs/json-to-pdf-0.7.5.jar') to gradle.

The project compiles fine but when I try to run JsonPDF.writeToFile I get this error:

FATAL EXCEPTION: main Process: com.trecone.jsonpdftest, PID: 14043 java.lang.NoClassDefFoundError: clojure.lang.Var at org.yogthos.JsonPDF.<clinit>(Unknown Source) at com.trecone.jsonpdftest.MainActivity.onCreate(MainActivity.java:121) at android.app.Activity.performCreate(Activity.java:5458) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470) at android.app.ActivityThread.access$900(ActivityThread.java:174) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:146) at android.app.ActivityThread.main(ActivityThread.java:5593) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) at dalvik.system.NativeStart.main(Native Method)

Question : background-color on header of table affecting the whole table.

Hello,

Thanks again for this awesome library.

I'm experiencing a behaviour that i would like to confirm if its expected.

I'm applying the background-color property to a table header, and the color is affecting all the rows of the table.

The json i'm using is the following:

[ { "top-margin":100, "bottom-margin":25, "left-margin":58, "right-margin":44, "size":"a4" }, [ "paragraph", [ "chunk", "Content before table." ] ], [ "paragraph", [ "chunk", "Some other content." ] ], [ "paragraph", [ "chunk", "Content before table." ] ], [ "table", { "header":[ "Row 1", "Row 2", "Row 3" ], "width":50, "border":false, "cell-border":false, "background-color":[ 100, 50, 100 ] }, [ [ "cell", { "colspan":2 }, "Foo" ], "Bar" ], [ "foo1", "bar1", "baz1" ], [ "foo2", "bar2", "baz2" ] ] ]

Wich produces the following pdf:

https://drive.google.com/open?id=1HmBQBF1Os0rijAlDqPWct7mDrYHQ9gD8

Is it expeted behaviour, or the color should only be applied to the header (only the first row)?.

Thanks in advance.

broken colspan with innertable in cell element

Hello again.

I think i found another bug:
Here is the JSON I'm using (formatted for better reading):

[
    {},
    [
        "table",
        [
            "c1r1",
            [
                "cell",
                [
                    "table",
                    [
                        "Inner table Col1",
                        "Inner table Col2",
                        "Inner table Col3"
                    ]
                ]
            ],
            "c3r1"
        ],
        [
            [
                "cell",
                {
                    "colspan": 3
                },
                "this should be a rowspan 3 for the complete row 2 of the table"
            ]
        ],
        [
            "c1r3",
            "c2r3",
            "c3r3"
        ],
        [
            "c1r4",
            "c2r4",
            "c3r4"
        ]
    ]
]

This results in a wrong interpretation of the colspan element:
image

using first usage exemple doesn't work

here is the exemple i tried to reproduce

String json = "{\"font\": {\"size\": 20}} \"stuff\" [\"paragraph\", \"foo bar\"]";
JsonPDF.writePDFToFile(json, "doc.pdf");

I'm running it into a groovy script.
I've got an exception

Caught: ExceptionConverter: java.io.IOException: The document has no pages.
ExceptionConverter: java.io.IOException: The document has no pages.
at com.lowagie.text.pdf.PdfPages.writePageTree(PdfPages.java:119)
at com.lowagie.text.pdf.PdfWriter.close(PdfWriter.java:1175)
at com.lowagie.text.pdf.PdfDocument.close(PdfDocument.java:830)
at com.lowagie.text.Document.close(Document.java:495)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at clojure.lang.Reflector.invokeMatchingMethod(Reflector.java:93)
at clojure.lang.Reflector.invokeNoArgInstanceMember(Reflector.java:298)
at clj_pdf.core$to_pdf.invoke(core.clj:762)
at json_to_pdf.core$_writePDFToStream.invoke(core.clj:11)
at json_to_pdf.core$_writePDFToFile.invoke(core.clj:15)
at org.yogthos.JsonPDF.writePDFToFile(Unknown Source)
at org.yogthos.JsonPDF$writePDFToFile.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
at test.run(test.groovy:451)
at groovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:257)
at groovy.lang.GroovyShell.run(GroovyShell.java:220)
at groovy.lang.GroovyShell.run(GroovyShell.java:150)
at groovy.ui.GroovyMain.processOnce(GroovyMain.java:588)
at groovy.ui.GroovyMain.run(GroovyMain.java:375)
at groovy.ui.GroovyMain.process(GroovyMain.java:361)
at groovy.ui.GroovyMain.processArgs(GroovyMain.java:120)
at groovy.ui.GroovyMain.main(GroovyMain.java:100)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:106)
at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:128)

Adding a repo to Maven

PS C:\apache-maven-3.5.3> mvn -v Apache Maven 3.5.3 (3383c37e1f9e9b3bc3df5050c29c8aff9f295297; 2018-02-24T14:49:05-05:00) Maven home: C:\apache-maven-3.5.3\bin\.. Java version: 10.0.1, vendor: Oracle Corporation Java home: C:\Program Files\Java\jdk-10.0.1 Default locale: en_US, platform encoding: Cp1252 OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"
I wasn't sure where to put the code in the main page so I looked around and found I needed to put it in pom.xml which should be at the root of the directory. I did not find it there and did a search if it was elsewhere. I created it and added 0.8.0 instead of 0.7.8 since that's the latest version at Clojars

Here's what my whole pom.xml looks like
<project> <seettings> <repositories> <repository> <id>clojars.org</id> <url>http://clojars.org/repo</url> </repository> </repositories> </dependency> <dependency> <groupId>json-to-pdf</groupId> <artifactId>json-to-pdf</artifactId> <version>0.8.0</version> </settings> </project>

Running
`PS C:\apache-maven-3.5.3> import .\book_metadata.json
import : The term 'import' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1

  • import .\book_metadata.json
  •   + CategoryInfo          : ObjectNotFound: (import:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException`
    

RFC json-to-pdf

Hi everyone.

I wonder if there is any technical specification like RFC for json-to-pdf. Is there any technical specification like RFC for json-to-pdf?

java.lang.UnsupportedOperationException: nth not supported on this type: PersistentHashMap

String doc = "{" +
            "    \"right-margin\": 10," +
            "    \"subject\": \"hello world\"," +
            "    \"creator\": \"Jane Doe\"," +
            "    \"doc-header\": [" +
            "      \"inspired by\"," +
            "      \"William Shakespeare\"" +
            "    ]," +
            "    \"bottom-margin\": 25," +
            "    \"pages\": true," +
            "    \"author\": \"someone\"," +
            "    \"header\": \"Page header text appears on each page\"," +
            "    \"left-margin\": 10," +
            "    \"title\": \"Test doc\"," +
            "    \"size\": \"a4\"," +
            "    \"letterhead\": [" +
            "      \"A simple Letter head\"" +
            "    ],\n" +
            "    \"orientation\": \"landscape\"," +
            "    \"font\": {" +
            "      \"size\": 11" +
            "    },\n" +
            "    \"footer\": \"Page footer text appears on each page (includes page number)\"," +
            "    \"top-margin\": 20" +
            "  }";

    InputStream inputStream = new ByteArrayInputStream(doc.getBytes());
    OutputStream outputStream = new ByteArrayOutputStream();
    JsonPDF.writeToStream(inputStream, outputStream);

Results in:

java.lang.UnsupportedOperationException: nth not supported on this type: PersistentHashMap
at clojure.lang.RT.nthFrom(RT.java:857)
at clojure.lang.RT.nth(RT.java:807)
at clj_pdf.core$write_doc.invoke(core.clj:879)
at clj_pdf.core$pdf.invoke(core.clj:932)
at json_to_pdf.core$parse.invoke(core.clj:16)
at json_to_pdf.core$_writeToStream.invoke(core.clj:22)
at org.yogthos.JsonPDF.writeToStream(Unknown Source)

Cannot convert JSON Object to PDF

Hi yogthos,

I'm trying to convert a json object into PDF.
But It is giving me Unknown source exception.

Find the code below.
JSONParser parser=new JSONParser();
Object object=parser.parse(new FileReader("TextFile.txt"));
JSONObject jsonObject = (JSONObject)object;
String jsonString = jsonObject.toJSONString();
JsonPDF.writeToFile(jsonString, dir + "MyFile.pdf");

JSON Object : TextFile.txt
{"balance":1000.1,"num":1000,"is_imp":true,"name":"Object"}

This is the error I'm getting

ERROR c.e.p.s.r.e.GeneralExceptionMapper - An unmapped exception was intercepted
java.lang.UnsupportedOperationException: nth not supported on this type: PersistentArrayMap
at clojure.lang.RT.nthFrom(RT.java:857) ~[clojure-1.6.0.jar:na]
at clojure.lang.RT.nth(RT.java:807) ~[clojure-1.6.0.jar:na]
at clj_pdf.core$write_doc.invoke(core.clj:822) ~[json-to-pdf-0.6.9.jar:na]
at clj_pdf.core$pdf.invoke(core.clj:875) ~[json-to-pdf-0.6.9.jar:na]
at json_to_pdf.core$_writeToFile.invoke(core.clj:12) ~[json-to-pdf-0.6.9.jar:na]
at org.yogthos.JsonPDF.writeToFile(Unknown Source) ~[json-to-pdf-0.6.9.jar:na]

Thanks
Aditya

java.lang.ClassCastException: java.io.ByteArrayInputStream cannot be cast to java.io.Reader

code:

String doc = "[{}, ["paragraph", "hello world"]]";
InputStream inputStream = new ByteArrayInputStream(doc.getBytes());
OutputStream outputStream = new ByteArrayOutputStream();
JsonPDF.writeToStream(inputStream, outputStream);

Results in:

java.lang.ClassCastException: java.io.ByteArrayInputStream cannot be cast to java.io.Reader
at cheshire.core$parse_stream.invoke(core.clj:190)
at cheshire.core$parse_stream.invoke(core.clj:186)
at json_to_pdf.core$parse.invoke(core.clj:16)
at json_to_pdf.core$_writeToStream.invoke(core.clj:22)
at org.yogthos.JsonPDF.writeToStream(Unknown Source)

Given that my hands are tied in that I can only provide an Inputstream why is the impl trying to convert to a Reader and more importantly what can I do to convince it otherwise?

Thanks.

Unable to use pagebreak tag from clj-pdf

Hi!

I know that pagebreak tag is not in your documentation, but I tried to use it because this simply 'translate' json to your clj-pdf format. But when I try to write to pdf a json that includes ["pagebreak"], it throws the following exception (with stacktrace):

Caused by: java.lang.Exception: invalid tag: :pagebreak in element: ["pagebreak"]
at clj_pdf.core$make_section.invoke(core.clj:665) [json-to-pdf-0.6.9.jar:]
at clj_pdf.core$append_to_doc.invoke(core.clj:681) [json-to-pdf-0.6.9.jar:]
at clj_pdf.core$add_item.invoke(core.clj:813) [json-to-pdf-0.6.9.jar:]
at clj_pdf.core$seq_to_doc.invoke(core.clj:853) [json-to-pdf-0.6.9.jar:]
at clj_pdf.core$pdf.invoke(core.clj:874) [json-to-pdf-0.6.9.jar:]
at json_to_pdf.core$_writeToFile.invoke(core.clj:12) [json-to-pdf-0.6.9.jar:]

I tried to follow this on clf-pdf core but I know nothing about clojure. It seems to recognize the :pagebreak tag but then sends the item again to make-section and is not one of the expected values. Could you tell me if I'm doing something wrong or if there is a way of achieve this? Is this tag not going to be available ever in json-to-pdf?

Thanks!

Scaling doesn't work for charts

I was trying to generate a smaller chart to display some test data, but the chart still just takes up a full page.

["chart",
{"type":"pie-chart", "title":"System Types", "xscale":0.3, "yscale":0.4, "align":"center"},
["AIX", 21], ["Windows", 23], ["Linux", 345]
]

Also is there a way to disable the grey background for pie-charts? I understand its purpose for line and bar charts, but it is pointless for a pie chart and makes it take up 2-3 times as much space as it needs to.

Possibility to use custom font-family.

Hello @yogthos, and once again thanks for this awesome library.

I was wondering if it would be possible to add support to specifying custom font-family in order to be used by the library.

The documentation illustrates that only certain font families are supported; ¿would it be possible to add support?

We would happily contribute if you can give a piece of advice on how to approach the change if needed.

Thanks in advance.

Kind regards.

how to make multiple lines in a table cell

Hi:

I'm using your library to create a letter head.
Playing around with table for layout, how do you make multiple lines in a cell (for example name + line break + address + line break + phone number)?
I tried multiple paragraphs in the cell to make multiples with no success.

Alternatively, if I used the cells for a new lines, how do I shrink the cell spacing/padding?

Thanks
Juan.

Compile error

I'm trying to compile "json-to-pdf:json-to-pdf:0.7.5" (gradle) on my Android app and I'm getting an error:

Error:(37, 13) Failed to resolve: json-to-pdf:json-to-pdf:0.7.5
Show in File, Show in Project Structure dialog

What am I doing wrong?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.