簡體   English   中英

在pypandoc(pandoc)中將較大的HTML文件轉換為docx的問題

[英]Issues converting larger HTML files to docx in pypandoc (pandoc)

我的問題與如何在pandoc執行中增加堆內存有關? ,但添加了特定於Python的組件。

背景:我正在嘗試自動生成科學報告。 我已將數據寫入HTML文件,並且想使用Pandoc.exe(文件轉換程序)轉換為.docx Word文檔。 我已經有了處理包含圖片,表格等的較小HTML文件的過程。 該文件為307KB。

當我嘗試轉換嵌入了多個圖形的較大文件(〜4.5MB)時,問題就開始了。 我一直在使用pypandoc進行轉換,如下所示:

import pypandoc
PANDOC_PATH = r"C:\Program Files\RStudio\bin\pandoc"

infile = savepath + os.sep + 'Results ' + name + '.html'
outfile = savepath + os.sep + 'Results ' + name + '.docx'

output = pypandoc.convert(source=infile, format='html', to='docx', \
outputfile=outfile, extra_args=["+RTS", "-K64m", "-RTS"])

但是我遇到了各種各樣的錯誤。 通常:

RuntimeError: Pandoc died with exitcode "2" during conversion: 
b"Stack space overflow: current size 33692 bytes.\nUse `+RTS -Ksize -RTS' to increase it.\n"

或者如果我將-Ksize的值提高到256m,則如下所示:

RuntimeError: Pandoc died with exitcode "1" during conversion: b'pandoc: out of memory\r\n'

有人可以在這里解釋發生了什么事,以及以某種方式可以解決這個難題嗎? 我考慮過的一種解決方案是使圖像縮小很多。 我一直在縮小(80-500KB)原始尺寸,其中每個圖像的寬度和高度取決於其原始尺寸:

data_uri = base64.b64encode(open(formats[graph][0], 'rb').read()).decode('utf-8')

img_tag = ('<img src="data:image/jpg;base64,{0}" height='+formats[graph][2][0]+'
             width='+formats[graph][2][1]+'>').format(data_uri) 

謝謝你的幫助

非常感謝user2407038對此的幫助!

最終,有兩個修復程序使我可以使用pypandoc將較大的HTML文件轉換為docx文件:

如所建議的,第一個是

增加堆的最大大小,例如,將-M2GB添加到extra_args

那是:

output = pypandoc.convert(source=infile, format='html', to='docx', outputfile=outfile, extra_args=["-M2GB", "+RTS", "-K64m", "-RTS"])


增加堆大小后,我還有第二個問題,所以我不確定該解決方案是否有效。 Python返回了這樣的錯誤消息:

RuntimeError:轉換期間Pandoc退出代碼為“ 1”:b“ pandoc:無法解碼字節'\\ x91':Data.Text.Internal.Encoding.Fusion.streamUtf8:無效的UTF-8流\\ n”

通過更改首先打開html文件的方式已修復該問題。 encoding關鍵字參數設置為'utf8'可使轉換正常進行:

report = open(savepath + os.sep + 'Results ' + name + '.html', 'w', encoding='utf8')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM