ArtifexSoftware / mupdf.js

JavaScript bindings for MuPDF
https://mupdfjs.readthedocs.io
GNU Affero General Public License v3.0
318 stars 17 forks source link

Page: Draw as SVG API #64

Closed steren closed 2 months ago

steren commented 2 months ago

Page.toPixmap() allows exporting the page to a raster image.

I am looking for an API to export as SVG.

I see mutool draw has the ability to export as svg. It also seems that another Wasm port of MuPDF has support for drawing as SVG. So I assume MuPDF has this capability, and it only needs to be exposed as an API in the JS library.

jamie-lemon commented 2 months ago

@ccxvii What do you think? Is it possible to expose such an API?

ccxvii commented 2 months ago

When we update the core to fix the bug with DocumentWriter you can use that API to create an SVG document.

var buf = new mupdf.Buffer()
var wri = new mupdf.DocumentWriter(buf, "svg", "")
var dev = wri.beginPage(page.getBounds())
page.run(dev, [1, 0, 0, 1, 0, 0])
wri.endPage()
wri.close()

// buf now contains SVG data for the page graphics
jamie-lemon commented 2 months ago

@steren This should now be available with the latest release of mupdf.js (0.2.1) on NPM - https://www.npmjs.com/package/mupdf , please confirm!

steren commented 2 months ago

Thanks, I confirm it works, here is my code:

    function renderPage(pdf, i) {

        const page = pdf.loadPage(i)

        const buf = new mupdf.Buffer()
        const wri = new mupdf.DocumentWriter(buf, "svg", "")
        const dev = wri.beginPage(page.getBounds())
        page.run(dev, [1, 0, 0, 1, 0, 0])
        wri.endPage()
        wri.close()

        const svgString = buf.asString();

        const svg = new Blob([svgString], { type: "image/svg+xml" });
        const img = new Image();
        img.src = URL.createObjectURL(svg);
        img.onload = function () {
            document.getElementById("render").appendChild(img);
        }

    }
steren commented 2 months ago

I would recommend:

  1. documenting this use case better
  2. Adding helper functions to the Page object (e.g. Page.toSVG())