Composables

nuxt-pdf exposes multiple composables, that you can access to easily create pdfs through vue code.

Options

Both of our composables, accept 2 seperate configuration options.

  • The documentOptions, allow you to customize the general layout of your document. You can find the options here.
  • The htmlOptions, allow you to customize the conversion of your HTML to a canvas. You can find the options here.

exportToPDF

exportToPDF allows you to usea native vue ref, to target either a native HTML element, or a Vue component, which will then be converted into a PDF.

The composable accepts 4 parameters:

  • The fileName
  • The component you wish to convert
  • The documentOptions
  • The HTMLOptions.

To learn more about the options, please refer here

<script setup lang="ts">const pdfSection = ref<HTMLElement | null>(null)const DOCUMENT_OPTIONS = {} // See all options: http://raw.githack.com/MrRio/jsPDF/master/docs/jsPDF.htmlconst HTML_OPTIONS = {} // See all options: http://raw.githack.com/MrRio/jsPDF/master/docs/module-html.html#~htmlconst export = () => {  await exportToPDF('FILE_NAME.pdf', pdfSection, DOCUMENT_OPTIONS, HTML_OPTIONS)}</script><template>  <div ref="pdfSection">    <h1>Hello world!</h1>  </div></template>

Tips & Tricks

  • Ensure that the section you want to export has a fixed width, to ensure the layout does not shift when exporting
  • Setting a fixed width and height, to match your document size, will lead to better results
  • Use the scale option in the document section, to slightly increase or decrease the size of the rendered html
  • Optimize your HTML to reduce the PDF file size

htmlToPDF

htmlToPdf allows you to pass an HTML string and format it into a PDF. This can allow you to futhur customize the behaviour of how the module interacts with your UI.

import { htmlToPdf } from '#imports'const openInWindow = async (HTMLElement: HTMLElement) => {  const pdf = await htmlToPdf(HTMLElement,    undefined,    {      html2canvas: {        scale: 0.7,        useCORS: true      }    })  const totalPages = pdf.getNumberOfPages()  const pdfHeight = pdf.getPageHeight()  await pdf.html('<b>I am a custom pdf!!!</b>', {    x: 20,    y: (pdfHeight - 50) * totalPages // place in the bottom  })  const blob = pdf.output('blob')  window.open(URL.createObjectURL(blob), '_blank')}