Javascript svg to pdf

svg2pdf.js

A javascript-only SVG to PDF conversion utility that runs in the browser leveraging jsPDF.

Installation

You can get svg2pf.js via npm:

npm install svg2pdf.js jspdf --save # or yarn add svg2pdf.js jspdf 

Since version 2.x, this repository no longer depends on a forked jsPDF but can be used with original MrRio/jsPDF.

If you want to use a development version from the repository, pay attention to the fact that the files in dist may reflect the last release version. So a simple package.json dependency link to the branch or revision will fail. See #102 for details.

Usage

import < jsPDF >from 'jspdf' import 'svg2pdf.js' const doc = new jsPDF() const element = document.getElementById('svg') doc .svg(element, < x, y, width, height >) .then(() => < // save the created pdf doc.save('myPDF.pdf') >) 

Have a look at the typings file for detailed documentation.

Other module formats

Importing is also possible via requirejs:

require.config(< baseUrl: './node_modules' >); require([ 'svg2pdf.js/dist/svg2pdf.umd.min', 'jspdf/dist/jspdf.umd.min' ], (svg2pdf, jsPDF) => ); 

Concerning custom fonts and non US-ASCII characters

If you want to use other than really basic fonts and characters you have to add them first before calling svg2pdf :

Reporting issues

Svg2pdf is by no means perfect. If you find something is not working as expected we are glad to receive an issue report from you. In order to be able to react efficiently we ask you to provide us with the necessary information.

Читайте также:  Автоматизированный сбор данных python

Building

If you want to play with the sources or build the minified js file yourself, check out the repository and use the npm scripts defined in package.json :

Testing

The test folder contains a set of unit tests. Each unit test has its own folder and contains exactly two files:

  • A spec.svg file that contains the svg to test
  • A reference.pdf file that is generated automatically and serves as reference for regression testing

You can run the tests using

npm run createreferences && npm run test-unit 

The tests use the Karma framework and run in a captured (headless) browser.

The createreferences script starts a server that automatically saves reference PDFs if they don’t already exist. You can omit this command if you just want to test for regression.

If you’re debugging and want to have visual feedback, you should switch the debug flag to true in test/unit/all.spec.js . This ensures that a new reference PDF will be created on every run. You might also want to disable some tests in the test/common/tests array.

Dependencies

License

Copyright (c) 2015-2023 yWorks GmbH

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

pre-press oriented node.js module to transform a SVG string into printable PDF file

License

arnaudjuracek/svg-to-pdf

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

pre-press oriented node.js module to transform a SVG string into printable PDF file

  • Support for this SVG elements:
    • Group inheritance (ie: will pass its color=green attribute to its children)
    • All PDFKit vector graphics supported operations
    • PDF file permissions and limitations w/ password support
    • PDF file metadatas edition (author, subject, keywords, etc…)
    • Length units support and implicit conversion to PDF points
    • Support for uncalibrated CMYK colors using device-cmyk() , as described in the SVG 2 Working draft 11
    • Pre-press inspired pre-flight process, which gives insight and warnings after generating a PDF file
    • Pre-press related features such as bleed area and printers marks:
      • crop marks
      • colors marks
      • registration marks
      • viewBox attribute is parsed only on the root element, so all system coordinates must be absolute
      • The preserveAspectRatio attribute is fully supported, but only on the element
      • elements are rendered only if they do not have complex structure (such as nested element)
      • Supported specific presentation attributes are:
        • dominant-baseline
        • font-family
        • font-size
        • letter-spacing
        • text-anchor
        • word-spacing

        Not supported, won’t be supported

        Use svgo beforehand to apply CSS styling as element attributes:

        full: false plugins: - inlineStyles: useMqs: - '' - screen - print - removeStyleElement - converStyleToAttrs

        NOTE: see svgo guide to read more about svgo config.

        $ npm install --save svg-to-pdf
        const SVG2PDF = require('svg-to-pdf') const options =  docPath: '/tmp/file.pdf', // All attributes refering to an external file path will be resolved from // this root path rootPath: process.cwd(), // color space can be either 'rgb' or 'cmyk' colorSpace: 'rgb', // SVG specification specifies that all unitless lengths are expressed in a // so-called "user unit", usually defaulting to pixel userUnit: 'px', // 'px', 'mm', 'cm', 'pt', 'in'… // Pre-press related features bleed: 0, // '10mm', '100px', 10 marks:  colors: true, crop: true, registration: true >, // Attach an additional [. files] array to the output, providing further // insights on PDF generation. // Be warned that files analysis can be perf heavy. createFilesReport = true, // PDF file options, see PDFKit pdfVersion: 1.3, userPassword: undefined, ownerPassword: undefined, permissions: undefined, title: '', subject: '', author: '', producer: 'arnaudjuracek/svg-to-pdf@semver', keywords: '' > // using Promises SVG2PDF(svgString, options) .then(( warnings, files >) => console.log(warnings)) .catch(error => console.error(error)) // using async/await ;(async () =>  const  warnings, files > = await SVG2PDF(svgString, options) console.log(warnings) >)()

        Note: for PDF file related options, see PDFKit options.

        $ npm test # run svg-to-pdf against test/sample.svg $ npm test -- --input=path/to/file.svg --output=path/to/output.svg --color-space=rgb|cmyk

        Источник

        Javascript svg to pdf

        Insert SVG into a PDF document created with PDFKit.

        npm install svg-to-pdfkit --save 
        SVGtoPDF(doc, svg, x, y, options); 

        If you prefer, you can add the function to the PDFDocument prototype:

        PDFDocument.prototype.addSVG = function(svg, x, y, options) < return SVGtoPDF(this, svg, x, y, options), this; >; 
        doc [PDFDocument] = the PDF document created with PDFKit svg [SVGElement or string] = the SVG object or XML code x, y [number] = the position where the SVG will be added options [Object] = > - width, height [number] = initial viewport, by default it's the page dimensions - preserveAspectRatio [string] = override alignment of the SVG content inside its viewport - useCSS [boolean] = use the CSS styles computed by the browser (for SVGElement only) - fontCallback [function] = function called to get the fonts, see source code - imageCallback [function] = same as above for the images (for Node.js) - documentCallback [function] = same as above for the external SVG documents - colorCallback [function] = function called to get color, making mapping to CMYK possible - warningCallback [function] = function called when there is a warning - assumePt [boolean] = assume that units are PDF points instead of SVG pixels - precision [number] = precision factor for approximative calculations (default = 3) 

        In the browser, it’s easier to register fonts (see here how) before calling SVGtoPDF. SVGtoPDF doesn’t wait for font loading with asynchronous XMLHttpRequest.

        Make sure to name the fonts with the exact pattern ‘MyFont’, ‘MyFont-Bold’, ‘MyFont-Italic’, ‘MyFont-BoldItalic’ (case sensitive), if the font is named font-family=»MyFont» in the svg. Missing Bold, Italic, BoldItalic fonts are simulated with stroke and skew angle.

        If your fonts don’t follow this pattern, or you want to register fonts at the moment they are encountered in the svg, you can use a custom fontCallback function.

        • shapes: rect, circle, path, ellipse, line, polyline, polygon
        • special elements: use, nested svg
        • text elements: text, tspan, textPath
        • text attributes: x, y, dx, dy, rotate, text-anchor, textLength, word-spacing, letter-spacing, font-size
        • styling: with attributes only
        • colors: fill, stroke & color (rgb, rgba, hex, string), fill-opacity, stroke-opacity & opacity
        • units: all standard units
        • transformations: transform, viewBox & preserveAspectRatio attributes
        • clip paths & masks
        • images
        • fonts
        • gradients
        • patterns
        • links
        • filters
        • text attributes: font-variant, writing-mode, unicode-bidi
        • foreignObject (#37)
        • other things I don’t even know they exist
        • Use an updated PDFKit version (≥0.8.1): see here how to build it, or use the prebuilt file in the examples folder.
        • There are bugs, please send issues and/or pull requests.
        • PDFKit, the JavaScript PDF generation library for Node and the browser.
        • For inserting SVG graphics into a PDFKit document there is also svgkit.
        • For the opposite conversion, from PDF to SVG, you can use Mozilla’s PDF.js.

        Источник

Оцените статью