![](/img/trans.png)
[英]UnicodeEncodeError: 'latin-1' codec can't encode character '\u2013' (writing to PDF)
[英]UnicodeEncodeError: 'latin-1' codec can't encode character '\u03bc'
我正在使用 python 庫PyFPDF創建一個 pdf,我的數據字符串之一包含一個稱為 mu 的“希臘小寫字母 μ”。 我收到上述錯誤。 如果我們從數據字符串中刪除這個希臘字母,代碼就可以完美運行。 我需要幫助將這個希臘字母解析為 pdf output。我的代碼如下:
str = "2-3 μg/day" pdf = FPDF('P', 'mm', 'A4') # Add a page pdf.add_page() # Set fonts and color pdf.set_font("Times", "B", size = 24) pdf.set_text_color(0, 0, 0) # insert the texts in pdf pdf.write(h = 10, txt = str) # save the pdf with name .pdf pdf.output("output.pdf")
提前致謝。
不確定為什么 PyFPDF 比FPDF 編輯器更迂腐,但是理論上您的文本需要 2 Fonts(時間和符號)。
“符號”通常用於希臘字母和一些符號,如:Ω、φ、≠、©......
pdf.set_font("Symbol",....
這里使用 Demo 顯示了一種常見的文本插入,通過替換 Arial 可以與兩者協同工作。
<?PHP
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage('P', 'A4');
$pdf->SetAutoPageBreak(true, 10);
$pdf->SetFont('Arial', '', 12);
$pdf->SetTopMargin(10);
$pdf->SetLeftMargin(10);
$pdf->SetRightMargin(10);
/* --- Text --- */
$pdf->SetFont('', 'B', 12);
$pdf->Text(21, 31, '2-3 μg/day');
$pdf->Output('created_pdf.pdf','I');
?>
對於時間和符號使用(使用您自己想要的偏移量)
/* --- Text --- */
$pdf->SetFont('Times', '', 12);
$pdf->Text(19, 32, '2-3');
/* --- Text --- */
$pdf->SetFont('Symbol', '', 12);
$pdf->Text(28, 32, 'μ');
/* --- Text --- */
$pdf->SetFont('Times', '', 12);
$pdf->Text(35, 32, 'g/day');
因此在你的情況下
str = "2-3 μg/day"
pdf = FPDF('P', 'mm', 'A4')
# Add a page
pdf.add_page()
# Set fonts and color
pdf.set_font("Times", "B", size = 24)
pdf.set_text_color(0, 0, 0)
# insert the texts in pdf
pdf.write(h = 10, txt = "2-3")
# Set font
pdf.set_font("Symbol", "B", size = 24)
# insert the texts in pdf
pdf.write(h = 15, txt = "μ")
# Set font
pdf.set_font("Times", "B", size = 24)
# insert the texts in pdf
pdf.write(h = 20, txt = "g/day")
# save the pdf with name .pdf
pdf.output("output.pdf")
否則使用包含文本和符號的字體,如“Arial”或“DejaVu”
pdf.set_font('Arial', 'B', 24)
pdf.write(h = 10, txt = "2-3 μg/day")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.