stamp_to_page.md
2023/10/08 categories:Code| tags:Code|
# -*- coding: utf-8 -*-
import fitz
import math
import unicodedata
def stamp_to_page(page: fitz.Page, x, y, r, line_width, color, str_u, str_m, str_b, fontsize_u, fontsize_m, fontsize_b):
t = 20 / 180 * math.pi
x0, x1, x2, x3 = x - r, x - r * math.cos(t), x + r * math.cos(t), x + r
y0, y1, y2, y3 = y - r, y - r * math.sin(t), y + r * math.sin(t), y + r
page.draw_line(fitz.Point(x1, y1), fitz.Point(x2, y1), color=color, width=line_width)
page.draw_line(fitz.Point(x1, y2), fitz.Point(x2, y2), color=color, width=line_width)
page.draw_circle(fitz.Point(x, y), radius=r, color=color, width=line_width)
insert_text(page, x0, y0, x3, y1, str_u, fontsize_u, color)
insert_text(page, x0, y1, x3, y2, str_m, fontsize_m, color)
insert_text(page, x0, y2, x3, y3, str_b, fontsize_b, color)
def insert_text(page, x0, y0, x1, y1, text, fontsize, color):
align = fitz.TEXT_ALIGN_CENTER
rect = fitz.Rect(fitz.Point(x0, y0), fitz.Point(x1, y1))
if is_japanese(text):
page.insert_textbox(rect, text, align=align, fontsize=fontsize, fontname='japan', color=color)
else:
page.insert_textbox(rect, text, align=align, fontsize=fontsize, color=color)
def is_japanese(string):
for ch in string:
if ch == '\n':
continue
name = unicodedata.name(ch)
if "CJK UNIFIED" in name or "HIRAGANA" in name or "KATAKANA" in name:
return True
return False
if __name__ == '__main__':
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
app = QtWidgets.QApplication(sys.argv)
view = QtWidgets.QGraphicsView()
view.setScene( QtWidgets.QGraphicsScene() )
doc = fitz.open()
page = doc.new_page(width=200, height=200)
qpixmap = stamp_to_page(page, 100, 100, 100, 5, (1.0, 0.0, 0.0))
pix = page.get_pixmap()
byte_array = QtCore.QByteArray( pix.tobytes() )
qpixmap = QtGui.QPixmap()
qpixmap.loadFromData(byte_array)
view.scene().addPixmap(qpixmap)
view.scene().setSceneRect(0, 0, qpixmap.width(), qpixmap.height())
view.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(200,200,200)))
view.setWindowTitle('PyMuPDF Test')
view.show()
app.exec()