Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. I've been using pdfkit and have been encpuntering # Pdfkit
  2. I've been using pdfkit and have been encountering this problem that says:
  3.  
  4. ```
  5. fs.readFileSync is undefined.
  6. ```
  7.  
  8. It took me a while to understand what the whole problem was, so let me walk you through my experience.
  9.  
  10. I needed a pdf generator on my ionic 3, angular 5 cross platform mobile app.
  11.  
  12. The problem is, the pdf generation library I've selected, which is `pdfkit`, is primarily designed for server-based code: for Node.js.
  13.  
  14. One distinction between node js and writing js for the browser is that node provides access to the file system through a module called `fs`.
  15.  
  16. However, when we try to utilize `pdfkit` on the browser, such as in the case of ionic apps, it does not run on the same environment it normally expects. This is why attempting to use `fs` shows an error because of undefined functions. It is simply not available on the browser.
  17.  
  18. ## What now?
  19. This sparks the following questions:
  20.  
  21. * If node servers use `fs` to handle files, what does the browser use?
  22.  
  23. * At what point, in `pdfkit` exactly, is this `fs` being used?
  24.  
  25. * What are my options when I want to use `pdfkit` on the browser?
  26.  
  27. Reading the documentation made it a little difficult for me to understand how to set it up on the browser. The following section explains how to go about it finding th answers to those questions and being able to use pdfkit on a browser.
  28.  
  29. ## Getting access to pdfkit
  30. Because I was using typescript for my project, I was having a difficult time importing the prebuilt `pdfkit` library. Was I supposed to use require or import?
  31.  
  32. In the end, I used ES6 notation that looks like the following:
  33.  
  34. ```
  35. import PDFDocument from 'pdfkit.js'
  36. ```
  37.  
  38. And using it looked like:
  39.  
  40. ```
  41. const a = new PDFDocument;
  42. ```
  43.  
  44. **Where exactly does the fs get used?**
  45.  
  46. fs is used when loading assets, namely fonts and images. So to address our problem of not relying on `fs`, what can we use instead?
  47.  
  48. The kind people working on `pdfkit` gave us the following options:
  49.  
  50. Serve your assets statically on the local server and use an XML request to get the data.
  51.  
  52. You can also try using `fetch` which is a new web technology for managing resources.
  53.  
  54. In any case, getting access to the resources array buffer is no longer retrieved through fs but instead the other interface options.
  55.  
  56. This should be done for any other assets, whether fonts or images.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement