Home > Blockchain >  json to pdf in javasript without any libraries
json to pdf in javasript without any libraries

Time:06-28

Is there any method that may be able to convert JSON data to pdf with using only pure Javascript , without using any libraries or packages

There is a requirement to create a single html page (done with help of webpack) for offline work . so I need to download some json as pdf and should not not use any libraries.

CodePudding user response:

I unfairly said in comments

no, until you write your own text/pdf parser. possible but not likely within my remaining lifetime,

So your challenge is to see (fast as you can) if you can use your Javascript coding skills to convert from raw:-

   {
        "text": {
            "text": "Hello World!",
            "points": 48 ,
            "x": 36 ,
            "y": 684
        }
    }

into this, and adapt it for other json objects, so perhaps add a page definition above to show text is on page 1 with a media box so as to relate the xy values to that page. Generally write the page structure first then the resources such as fonts then the text mapped to font and position.

%PDF-1.0
%µ¶

1 0 obj
<</Type/Catalog/Pages 2 0 R>>
endobj

2 0 obj
<</Kids[3 0 R]/Count 1/Type/Pages/MediaBox[0 0 595 792]>>
endobj

3 0 obj
<</Type/Page/Parent 2 0 R/Contents 4 0 R/Resources<<>>>>
endobj

4 0 obj
<</Length 58>>
stream
q
BT
/ 96 Tf
1 0 0 1 36 684 Tm
(Hello World!) Tj
ET
Q

endstream
endobj

xref
0 5
0000000000 65536 f 
0000000016 00000 n 
0000000062 00000 n 
0000000136 00000 n 
0000000209 00000 n 

trailer
<</Size 5/Root 1 0 R>>
startxref
316
%%EOF

Note there is no font so this example is just step one, the next step is much harder and that is how to include the font description, so for a hint see enter image description here

So contrary to using raw JS I suggest there is already an exceptionally very good Apache-2.0 license 3 MB cross platform API/CLI library that converts Json to PDF. So above one liner uses amazing tiny powerful https://pdfcpu.io/

  • Related