2017-11-09 3 views
0

저는 python에서 pyfpdf를 사용하여 pdf 파일을 생성하고 있습니다. 나는 내 파일 시스템에 이미지로 저장하지 않고도 pdf 파일에 삽입 할 Base64를 가지고 있습니다. 그러나 pyfpdf 이미지 함수는 파일 경로 만 허용합니다.pyfpdf를 사용하여 Base64 이미지를 PDF에 삽입하십시오.

fpdf.image(name, x = None, y = None, w = 0, h = 0, type = '', link = '') 

직접 미리 파일 시스템에 저장할 필요없이 메모리로부터의베이스 64 또는 완충 화상을 삽입하는 방법 (핵)이 있는가? 심지어 github에서 소스 코드를 확인하고 생각할 수도 없었습니다.

링크 : https://github.com/reingart/pyfpdf/tree/master/fpdf

+1

'fpdf'를 서브 클래스 화하고'Load_resource'를 오버라이드하여'BytesIO' 파일과 유사한 객체를 반환 할 수 있습니다. – pvg

+0

그게 좋은 생각이야. 내가 붙어 있어도 자세한 답변을 게시 할 수 있다면 도움이 될 것입니다. –

+2

모든 이미지 파싱 코드는'load_resource'를 호출합니다. 명확하지 않은 것이 있으면 특정 질문을하십시오. 다른 방법으로는, 다른 pdf 라이브러리를 사용하여 탐색 할 수도 있습니다.이 라이브러리는 신중하지 않은 혼란 (PHP 포트입니다)을 나타냅니다. – pvg

답변

1

@pvg이 base64로 기능과 트릭을 load_resource 기능을 않는 무시 코멘트에서 언급 한 바와 같이.

import base64,io 

def load_resource(self, reason, filename): 
    if reason == "image": 
     if filename.startswith("http://") or filename.startswith("https://"): 
      f = BytesIO(urlopen(filename).read()) 
     elif filename.startswith("data"): 
      f = filename.split('base64,')[1] 
      f = base64.b64decode(f) 
      f = io.BytesIO(f) 
     else: 
      f = open(filename, "rb") 
     return f 
    else: 
     self.error("Unknown resource loading reason \"%s\"" % reason) 

편집 :

이 PDF 파일에 이미지를 삽입 할 수있는 샘플 코드입니다. 코드의 일부 설명에 주석을 달았습니다.

from fpdf import FPDF 
import os 
import io 
import base64 


class PDF(FPDF): 

    def load_resource(self, reason, filename): 
     if reason == "image": 
      if filename.startswith("http://") or filename.startswith("https://"): 
       f = BytesIO(urlopen(filename).read()) 
      elif filename.startswith("data"): 
       f = filename.split('base64,')[1] 
       f = base64.b64decode(f) 
       f = io.BytesIO(f) 
      else: 
       f = open(filename, "rb") 
      return f 
     else: 
      self.error("Unknown resource loading reason \"%s\"" % reason) 


    def sample_pdf(self,img,path): 

     self.image(img,h=70,w=150,x=30,y=100,type="jpg") 
     #make sure you use appropriate image format here jpg/png 
     pdf.output(path, 'F') 

if __name__ == '__main__': 
    img = # pass your base64 image 
    # you can find sample base64 here : https://pastebin.com/CaZJ7n6s 

    pdf = PDF() 
    pdf.add_page() 
    pdf_path = # give path to where you want to save pdf 
    pdf.sample_pdf(img,pdf_path) 
관련 문제