1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
| import streamlit as st from streamlit_drawable_canvas import st_canvas import numpy as np import cv2 from PIL import Image import io import fitz import os import pandas as pd
st.set_page_config( layout="wide", )
dict_pdf = { "測量工程抽查表": "6-27.pdf", "土方工程抽查表": "6-29.pdf", "模板工程抽查表": "6-30.pdf", "鋼筋工程抽查表": "6-31.pdf", "其他": "" }
st.sidebar.title("✍ PDF 簽名工具")
page = st.sidebar.selectbox("選擇頁面", ["手繪簽名", "查看表單"])
if page == "手繪簽名":
save_folder = "saved_pdfs" os.makedirs(save_folder, exist_ok=True) form_selection = st.sidebar.selectbox("選擇抽查表", list(dict_pdf.keys()))
file_name = "./pdfs/"+dict_pdf[form_selection]
if form_selection == "其他": uploaded_file = st.file_uploader("上傳 PDF", type=["pdf"]) else: with open(file_name, "rb") as f: uploaded_file = f.read()
if uploaded_file: if form_selection == "其他": pdf_bytes = uploaded_file.read() else: pdf_bytes = uploaded_file
document = fitz.open("pdf", pdf_bytes) page = document.load_page(0) pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0)) original_width, original_height = pix.width, pix.height background_image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
canvas_result = st_canvas( fill_color="rgba(0, 0, 0, 0)", stroke_width=3, stroke_color="black", background_image=background_image, height=pix.height, width=pix.width, drawing_mode="freedraw", key="canvas", )
if canvas_result.image_data is not None: signature_data = canvas_result.image_data signature = cv2.cvtColor(signature_data, cv2.COLOR_RGBA2BGRA)
signed_images = []
y_offset, x_offset = 0,0
for page_num in range(len(document)): page = document.load_page(page_num) pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0)) image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
open_cv_image = np.array(image) open_cv_image = cv2.cvtColor(open_cv_image, cv2.COLOR_RGB2BGRA)
sig_h, sig_w, _ = signature.shape img_h, img_w, _ = open_cv_image.shape
adjusted_y_offset = int((y_offset / original_height) * img_h) adjusted_x_offset = int((x_offset / original_width) * img_w)
if adjusted_y_offset + sig_h > img_h: sig_h = img_h - adjusted_y_offset if adjusted_x_offset + sig_w > img_w: sig_w = img_w - adjusted_x_offset
resized_signature = cv2.resize(signature, (sig_w, sig_h))
for c in range(0, 3): open_cv_image[adjusted_y_offset:adjusted_y_offset+sig_h, adjusted_x_offset:adjusted_x_offset+sig_w, c] = \ resized_signature[:, :, c] * (resized_signature[:, :, 3] / 255.0) + \ open_cv_image[adjusted_y_offset:adjusted_y_offset+sig_h, adjusted_x_offset:adjusted_x_offset+sig_w, c] * (1.0 - resized_signature[:, :, 3] / 255.0)
signed_image = Image.fromarray(cv2.cvtColor(open_cv_image, cv2.COLOR_BGRA2RGBA)) signed_images.append(signed_image)
pdf_output = io.BytesIO() signed_images[0].save(pdf_output, "PDF", resolution=100.0, save_all=True, append_images=signed_images[1:]) pdf_output.seek(0)
if st.button("儲存", type='primary'): base_file_name = form_selection if form_selection != "其他" else "custom" existing_files = [f for f in os.listdir(save_folder) if f.startswith(base_file_name)] file_count = len(existing_files) + 1 output_file_name = f"{base_file_name}_{file_count}.pdf" save_path = os.path.join(save_folder, output_file_name)
with open(save_path, "wb") as f: f.write(pdf_output.getbuffer()) st.success(f"已將簽名後的 PDF 保存到: {save_path}")
elif page == "查看表單":
save_folder = "saved_pdfs" os.makedirs(save_folder, exist_ok=True)
saved_forms = os.listdir(save_folder)
classified_forms = {} for form in saved_forms: form_type = form.rsplit('_', 1)[0] if form_type not in classified_forms: classified_forms[form_type] = [] classified_forms[form_type].append(form)
df = pd.DataFrame( [(key, form) for key, forms in classified_forms.items() for form in forms], columns=["表單類型", "文件名"] )
selected_forms = st.multiselect("選擇要顯示的表單", df["文件名"])
if selected_forms:
for form in selected_forms: form_path = os.path.join(save_folder, form) st.markdown(f"#### {form}") pdf_doc = fitz.open(form_path) for page_num in range(len(pdf_doc)): page = pdf_doc.load_page(page_num) pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0)) img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) st.image(img, caption=f"第 {page_num + 1} 頁")
else: st.write("目前沒有已保存的表單。")
|