How to insert image in mupdf library

1.6k Views Asked by At

I am using mupdf to sign a pdf.

And I succeed to sign a annotation in pdf with function "pdf_update_ink_appearance"

Now I'm trying to insert an image into pdf.

I add below codes to insert image:

image = fz_new_image_from_file(ctx, "/storage/emulated/0/a.jpg");

fz_fill_image(ctx, dev, image, &page_ctm, 1.0f);

And the image doesn't show up in pdf.

I try another method, but the image also can't show up in pdf.

How to add a transparent image to PDF with mupdf using SMask?

Can anyone help this situation?

Thanks.

1

There are 1 best solutions below

0
On

I am one of PyMuPDF's authors (a Python binding for MuPDF) and solved this exact task. You might have a look at the source code in GitHub.

The basic process is:

Create an image and then a pixmap from the file. If this pixmap has alpha (i.e. transparency), create another pixmap containg the alpha bytes and link like follows. After this add the main pixmap to the PDF. Finally Add an XObject referencing it to the page's /Resources, and invoke the XObject with a "Do" operator in the page's /Contents object.

if (filename)
{
    image = fz_new_image_from_file(gctx, filename);
    pix = fz_get_pixmap_from_image(gctx, image, NULL, NULL, 0, 0);
    if (pix->alpha == 1)
    {
        j = pix->n - 1;
        pm = fz_new_pixmap(gctx, NULL, pix->w, pix->h, seps, 0);
        s = pix->samples;
        t = pm->samples;
        for (i = 0; i < pix->w * pix->h; i++)
            t[i] = s[j + i * pix->n];
        mask = fz_new_image_from_pixmap(gctx, pm, NULL);
        zimg = fz_new_image_from_pixmap(gctx, pix, mask);
        fz_drop_image(gctx, image);
        image = zimg;
        zimg = NULL;
    }
}

Do have a look at file fitz.i and search for function insertImage. It's an SWIG interface file, but that part is plain C interfacing with MuPDF.