2012-04-11 195 views
5

對於我的項目,我從另一個程序中獲取純文本文件(report.txt)。它都以純文本格式。如果你在記事本中打開它,它看起來不錯(和純文本文件一樣)。當我在Word中打開文件並顯示段落時,我會看到...空格和後退P的排列順序。在Python中將純文本轉換爲PDF

我需要將此文件轉換爲PDF並添加一些其他PDF頁面才能生成最終的PDF。所有這些都發生在Python中。

我無法將report.txt轉換爲pdf。我有ReportLab,並且能夠讀取文件並進行一些更改(如將文本更改爲Courier),但間距會丟失。當文件被讀取時,它似乎剝離了任何額外的空間。

問題: a)是否有更簡單的方法將report.txt轉換爲pdf? b)如果沒有,當我閱讀文件時是否有辦法保留我的空間? c)或者是否有一個參數我從我的段落樣式,將保持原來的樣子失蹤?

這裏是我的代碼:

# ------------------------------------ 
# Styles 
# ------------------------------------ 

styleSheet = getSampleStyleSheet() 
mystyle = ParagraphStyle(name='normal',fontName='Courier', 
         fontSize=10, 
         alignment=TA_JUSTIFY, 
         leading=1.2*12, 
         parent=styleSheet['Normal'])  

#=====================================================================================  
model_report = 'report.txt' 

# Create document for writing to pdf 
doc = SimpleDocTemplate(str(pdfPath), \ 
         rightMargin=40, leftMargin=40, \ 
         topMargin=40, bottomMargin=25, \ 
         pageSize=A4) 
doc.pagesize = portrait(A4) 

# Container for 'Flowable' objects 
elements = []  

# Open the model report 
infile = file(model_report).read() 
report_paragraphs = infile.split("\n") 

for para in report_paragraphs: 
    para1 = '<font face="Courier" >%s</font>' % para 
    elements.append(Paragraph(para1, style=mystyle)) 
doc.build(elements) 

回答

2

ReportLab的是,你可以從本頁面右側的「相關」的問題看到常用的recommendation--。

您是否試過用StyleSheet['Normal']創建文本?也就是說,如果你用以下方法得到正確的輸出結果,那麼問題與你的風格有某種關係。

Paragraph(para1, style=StyleSheet['Normal']) 
+0

普通不起作用完全相同,因此爲什麼我試圖創建自己的。 – user1327390 2012-04-16 17:29:11

+1

由於正常*應該*工作,我建議你找出爲什麼它不。從文檔中複製粘貼示例,如果仍然不起作用,則ReportLab的安裝有問題。然後將「report.txt」添加到混合中,如果它打破它,請檢查您的文件編碼 - 可能是UTF16而不是ascii?祝你好運。 – alexis 2012-04-17 15:45:39

0

我有類似的問題。我解決了這個代碼:

from reportlab.lib.pagesizes import letter 
from reportlab.pdfgen import canvas 
from reportlab.lib.utils import ImageReader 
from PIL import Image 

# ..... 
# ..... some exta code unimportant for this issue.... 
# .... 


# here it is 
ptr = open("tafAlternos.txt", "r") # text file I need to convert 
lineas = ptr.readlines() 
ptr.close() 
i = 750 
numeroLinea = 0 

while numeroLinea < len(lineas): 
    if numeroLinea - len(lineas) < 60: # I'm gonna write every 60 lines because I need it like that 
     i=750 
     for linea in lineas[numeroLinea:numeroLinea+60]:  
      canvas.drawString(15, i, linea.strip()) 
      numeroLinea += 1 
      i -= 12 
     canvas.showPage() 
    else: 
     i = 750 
     for linea in lineas[numeroLinea:]: 
      canvas.drawString(15, i, linea.strip()) 
      numeroLinea += 1 
      i -= 12 
     canvas.showPage() 

全文看起來原始文本文件

+0

你可以編輯顯示你如何創建畫布和PDF文件? – pekasus 2017-04-10 17:19:32