python pdf转图片 带界面
时间: 2023-05-29 21:07:23 浏览: 63
以下是Python代码实现PDF转图片带界面,使用了PyQt5和PyMuPDF库:
```python
import sys
import os
import fitz
from PyQt5.QtWidgets import QApplication, QFileDialog, QMainWindow, QLabel, QPushButton, QVBoxLayout, QWidget, QMessageBox
from PyQt5.QtGui import QImage, QPixmap
class PdfToImage(QMainWindow):
def __init__(self):
super().__init__()
self.title = "PDF转图片"
self.setWindowTitle(self.title)
self.left = 50
self.top = 50
self.width = 400
self.height = 120
self.initUI()
def initUI(self):
layout = QVBoxLayout()
self.label = QLabel("请选择PDF文件")
layout.addWidget(self.label)
self.button = QPushButton("选择文件")
self.button.clicked.connect(self.selectFile)
layout.addWidget(self.button)
self.setLayout(layout)
def selectFile(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getOpenFileName(self, "选择PDF文件", "", "PDF Files (*.pdf)", options=options)
if fileName:
self.convertPdfToImage(fileName)
def convertPdfToImage(self, fileName):
try:
doc = fitz.open(fileName)
for i in range(doc.page_count):
page = doc.load_page(i)
pix = page.get_pixmap()
image = QImage(pix.samples, pix.width, pix.height, pix.stride, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(image)
pixmap.save(os.path.splitext(fileName)[0] + "-page-" + str(i+1) + ".jpg", "jpg")
self.label.setText("转换完成")
QMessageBox.information(self, "完成", "转换完成")
except Exception as e:
self.label.setText("转换失败")
QMessageBox.critical(self, "错误", "转换失败:" + str(e))
if __name__ == "__main__":
app = QApplication(sys.argv)
pdfToImage = PdfToImage()
pdfToImage.show()
sys.exit(app.exec_())
```
运行该代码会弹出一个带有“选择文件”按钮的窗口,点击按钮可以选择要转换的PDF文件。选择完成后,该程序将会把每一页PDF文件转换成JPEG格式的图片,并保存在同一目录下。转换完成后会弹出一个提示框。