Hopding / pdf-lib

Create and modify PDF documents in any JavaScript environment
https://pdf-lib.js.org
MIT License
6.74k stars 645 forks source link

Cannot add an image on top of a shape #1541

Closed furstenheim-goodnotes closed 9 months ago

furstenheim-goodnotes commented 10 months ago

What were you trying to do?

Hi, I have a pdf that contains a shape and some text. I'm trying to render a png on top of the content.

How did you attempt to do it?

const {PDFDocument, BlendMode} = require('pdf-lib')
const fs = require('fs/promises')
main()
    .then(function () {
        console.log('finished')
    }, function (err) {
        console.error('error', err)
    })
async function main () {
    const pdfB = await fs.readFile('./input-pdf-with-blank-overlay-2.pdf')
    const doc = await PDFDocument.load(pdfB)
    const buffer = await fs.readFile('./merge.png')
    const pdfImage = await doc.embedPng(buffer)
    const page = doc.getPage(0)
    page.drawImage(pdfImage, {
        x: 0,
        y: 100,
        width: page.getWidth(),
        height: page.getHeight(),

    })
    const exportedPage = await doc.save()
    await fs.writeFile('example-with-overlay.pdf', exportedPage)
}

I've tried with different blend modes

merge

input-pdf-with-blank-overlay-2.pdf

What actually happened?

The image was over the text but below the rectangle.

What did you expect to happen?

I would expect to have the image over the rectangle, or to have some way of controlling the order

How can we reproduce the issue?

const {PDFDocument, BlendMode} = require('pdf-lib')
const fs = require('fs/promises')
main()
    .then(function () {
        console.log('finished')
    }, function (err) {
        console.error('error', err)
    })
async function main () {
    const pdfB = await fs.readFile('./input-pdf-with-blank-overlay-2.pdf')
    const doc = await PDFDocument.load(pdfB)
    const buffer = await fs.readFile('./merge.png')
    const pdfImage = await doc.embedPng(buffer)
    const page = doc.getPage(0)
    page.drawImage(pdfImage, {
        x: 0,
        y: 100,
        width: page.getWidth(),
        height: page.getHeight(),

    })
    const exportedPage = await doc.save()
    await fs.writeFile('example-with-overlay.pdf', exportedPage)
}

Version

1.17.1

What environment are you running pdf-lib in?

Node

Checklist

Additional Notes

Thanks so much for the project

furstenheim-goodnotes commented 10 months ago

Example output

example-with-overlay.pdf

furstenheim-goodnotes commented 9 months ago

By the spec, annotations are rendered on top of images