debug PDF generation

This commit is contained in:
2024-11-08 18:42:07 +09:00
parent 4e4bd7ac5d
commit a0c3a82720
2 changed files with 52 additions and 32 deletions

View File

@ -385,26 +385,34 @@ class SumasenExcel:
except Exception: except Exception:
cell_height = 20 # デフォルト値 cell_height = 20 # デフォルト値
# 最小サイズを設定 # マージンの設定(ピクセル単位)
cell_width = max(cell_width, 100) margin_horizontal = 4 # 左右のマージン
cell_height = max(cell_height, 20) margin_vertical = 2 # 上下のマージン
# 最大サイズを設定 # マージンを考慮したセルの実効サイズを計算
max_width = 800 effective_cell_width = cell_width - (margin_horizontal * 2)
max_height = 600 effective_cell_height = cell_height - (margin_vertical * 2)
cell_width = min(cell_width, max_width)
cell_height = min(cell_height, max_height) # 最小サイズを設定(マージンを考慮)
effective_cell_width = max(effective_cell_width, 92) # 100 - (4 * 2)
effective_cell_height = max(effective_cell_height, 16) # 20 - (2 * 2)
# 最大サイズを設定(マージンを考慮)
max_width = 792 # 800 - (4 * 2)
max_height = 596 # 600 - (2 * 2)
effective_cell_width = min(effective_cell_width, max_width)
effective_cell_height = min(effective_cell_height, max_height)
# アスペクト比を保持しながらリサイズ # アスペクト比を保持しながらリサイズ
img_width, img_height = img.size img_width, img_height = img.size
img_aspect = img_width / img_height img_aspect = img_width / img_height
cell_aspect = cell_width / cell_height cell_aspect = effective_cell_width / effective_cell_height
if img_aspect > cell_aspect: if img_aspect > cell_aspect:
width = cell_width width = effective_cell_width
height = int(width / img_aspect) height = int(width / img_aspect)
else: else:
height = cell_height height = effective_cell_height
width = int(height * img_aspect) width = int(height * img_aspect)
# 画像をリサイズ # 画像をリサイズ
@ -419,8 +427,20 @@ class SumasenExcel:
from openpyxl.drawing.image import Image as XLImage from openpyxl.drawing.image import Image as XLImage
excel_image = XLImage(img_byte_arr) excel_image = XLImage(img_byte_arr)
# 画像の配置 # 画像のオフセット位置を設定(マージンを適用)
excel_image.anchor = f"{column_letter}{cell.row}" from openpyxl.drawing.spreadsheet_drawing import OneCellAnchor, AnchorMarker
from openpyxl.utils.units import pixels_to_EMU
# セルの左上を基準に、マージン分オフセットした位置に配置
col_offset = pixels_to_EMU(margin_horizontal)
row_offset = pixels_to_EMU(margin_vertical)
# マージンを考慮した配置
marker = AnchorMarker(col=cell.column - 1, colOff=col_offset,
row=cell.row - 1, rowOff=row_offset)
anchor = OneCellAnchor(_from=marker, ext=None)
excel_image.anchor = anchor
# 画像をワークシートに追加 # 画像をワークシートに追加
worksheet.add_image(excel_image) worksheet.add_image(excel_image)
@ -432,9 +452,10 @@ class SumasenExcel:
import traceback import traceback
logging.error(traceback.format_exc()) logging.error(traceback.format_exc())
return field_value return field_value
else: elif image_path and not os.path.exists(image_path):
if image_path:
logging.warning(f"画像ファイルが存在しません: {image_path}") logging.warning(f"画像ファイルが存在しません: {image_path}")
return "" #空欄にする
else:
return field_value return field_value
except Exception as e: except Exception as e:

View File

@ -2768,19 +2768,18 @@ def export_excel(request, zekken_number, event_code):
if format_type.lower() == 'pdf': if format_type.lower() == 'pdf':
try: try:
# 一時ディレクトリを作成 # パスとファイル名に分離
temp_dir = tempfile.mkdtemp() file_dir = os.path.dirname(excel_path) # パス部分の取得
temp_excel = os.path.join(temp_dir, f'certificate_{zekken_number}.xlsx') file_name = os.path.basename(excel_path) # ファイル名部分の取得
temp_pdf = os.path.join(temp_dir, f'certificate_{zekken_number}.pdf')
# Excelファイルを一時ディレクトリにコピー # ファイル名の拡張子をpdfに変更
shutil.copy2(excel_path, temp_excel) base_name = os.path.splitext(file_name)[0] # 拡張子を除いたファイル名
new_file_name = base_name + ".pdf" # 新しい拡張子を追加
# 一時ディレクトリのパーミッションを設定 # 新しいパスを作成
os.chmod(temp_dir, 0o777) pdf_path = os.path.join(file_dir, new_file_name)
os.chmod(temp_excel, 0o666)
logger.info(f"Converting Excel to PDF in temp directory: {temp_dir}") logger.info(f"Converting Excel to PDF in directory: {file_dir}")
# LibreOfficeを使用してExcelをPDFに変換 # LibreOfficeを使用してExcelをPDFに変換
conversion_command = [ conversion_command = [
@ -2789,8 +2788,8 @@ def export_excel(request, zekken_number, event_code):
'--convert-to', '--convert-to',
'pdf', 'pdf',
'--outdir', '--outdir',
temp_dir, file_dir,
temp_excel excel_path
] ]
logger.debug(f"Running conversion command: {' '.join(conversion_command)}") logger.debug(f"Running conversion command: {' '.join(conversion_command)}")
@ -2811,7 +2810,7 @@ def export_excel(request, zekken_number, event_code):
logger.debug(f"Conversion output: {process.stdout}") logger.debug(f"Conversion output: {process.stdout}")
# PDFファイルの存在確認 # PDFファイルの存在確認
if not os.path.exists(temp_pdf): if not os.path.exists(pdf_path):
logger.error("PDF conversion failed - output file not found") logger.error("PDF conversion failed - output file not found")
return Response( return Response(
{"error": "PDF conversion failed - output file not found"}, {"error": "PDF conversion failed - output file not found"},
@ -2819,7 +2818,7 @@ def export_excel(request, zekken_number, event_code):
) )
# PDFファイルを読み込んでレスポンスを返す # PDFファイルを読み込んでレスポンスを返す
with open(temp_pdf, 'rb') as pdf_file: with open(pdf_path, 'rb') as pdf_file:
pdf_content = pdf_file.read() pdf_content = pdf_file.read()
response = HttpResponse(pdf_content, content_type='application/pdf') response = HttpResponse(pdf_content, content_type='application/pdf')