QPDF Render to QImage is giving me Transparent output QImage
-
Hi, I am using Qt 6.4 on Windows 11 with MSVC 2019 64-bit.
I'm encountering an issue where I load PDFs and render them to QImage and then save them as BMP. While this works fine for some PDFs, others render with a transparent background. This means the text from the PDF is visible, but instead of a solid background, it is transparent.
Here's the code I'm using:
QString pdfPath = QFileDialog::getOpenFileName(this, "Open PDF", "", "PDF Files (*.pdf)"); if(!pdfPath.isEmpty()) { return; } QPdfDocument pdfDoc; QPdfDocumentRenderOptions options; options.setRenderFlags(QPdfDocumentRenderOptions::RenderFlag::Annotations | QPdfDocumentRenderOptions::RenderFlag::TextAliased | QPdfDocumentRenderOptions::RenderFlag::OptimizedForLcd); if (pdfDoc.load(pdfPath) == QPdfDocument::Error::None) { qreal targetDPI = 300.0; QSizeF pageSize = pdfDoc.pagePointSize(0); qDebug() << "=> PDF width and height: " << pageSize.width() << " - " << pageSize.height(); int widthInPixels = qRound(pageSize.width() * targetDPI / 72.0); int heightInPixels = qRound(pageSize.height() * targetDPI / 72.0); qDebug() << "==> Calculated Width and Height in pixels: " << widthInPixels << " - " << heightInPixels; QImage image = pdfDoc.render(0, QSize(widthInPixels, heightInPixels)); qDebug() << "==> Rendered Image format: " << image.format(); image.save("output.bmp", "BMP"); qDebug() << "==> Image Saved"; }
I've tried adjusting the DPI and QPdfDocumentRenderOptions, but the issue persists for certain PDFs—they are converted into QImage correctly but with a transparent background.
Any advice or suggestions on how to resolve this would be greatly appreciated.
-
They are converted that way because they contain no background. After PDF v1.4 the resulting pixel on a page is the composition of all overlaying graphic objects, each of which may carry an alpha component. If there is no explicit opaque object (e.g. a white rectangle) overlaying the entire page, under all the other objects, then there is no background where there are no overlying objects. It could be that the "working" images are PDF v1.3 or have an explicit background layer.
You could:
- adjust the PDFs at source, or
- paint the resulting image over a filled canvas image to obtain an image guaranteed to have a background