0
doc = fitz.open()
pdf = fitz.open("in.pdf")
for page in pdf:
    pix = page.get_pixmap(matrix=fitz.Matrix(7, 7))
    im = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
    im = cvtColor(array(im), COLOR_RGB2GRAY)
    page = "page-%i.png" % page.number
    Image.fromarray(im).save(page)
    img = fitz.open(page)  # open pic as document
    rect = img[0].rect  # pic dimension
    pdfbytes = img.convert_to_pdf()  # make a PDF stream
    img.close()
    os.remove(page)
    imgPDF = fitz.open("pdf", pdfbytes)  # open stream as PDF
    page = doc.new_page(width = rect.width, height = rect.height)  # pic dimension
    page.show_pdf_page(rect, imgPDF, 0)  # image fills the page
doc.save("out.pdf")

I now have to save the np array as png and then convert to pdf. I would like to ask if there is a more direct way?

R.Q Luo
  • 1
  • 1

1 Answers1

0

From numpy array, you can do the following:

import io
import fitz
import numpy as np
from PIL import Image

doc = fitz.open() 

image = np.random.rand(100, 100, 3) * 255
image = image.astype('uint8')

PIL_image = Image.fromarray(image[:,:,::-1])
bio = io.BytesIO()
PIL_image.save(bio, 'jpeg')

img = fitz.open('jpg', bio.getvalue())
pdfbytes = img.convert_to_pdf()
rect = img[0].rect
img.close()

imgPDF = fitz.open("pdf", pdfbytes)
page = doc.new_page(width=rect.width, height=rect.height)
page.show_pdf_page(rect, imgPDF, 0)

doc.save('example.pdf')
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 16 '23 at 06:28