2010-08-10 4 views
8

더 나은 품질을 제공하기 때문에 matplotlib의 일부 플롯을 pdf 형식으로 저장했습니다. ReportLab을 사용하여 PDF 이미지에 PDF 이미지를 포함하려면 어떻게합니까? 편리한 메소드 Image (파일 경로)가이 형식에서 작동하지 않습니다.ReportLab (Python)을 사용하여 PDF 문서의 PDF 이미지

감사합니다. reportlab.graphics에서

답변

-3

사용 renderPDF가

+3

이 올바르지 않습니다. renderPDF는 기존 문서를 사용하여 PDF를 생성합니다. 포스터가 원하는 것과 정반대입니다. –

2

ReportLab's FAQ에 따르면이 ReportLab PLUS에서만 가능하다 가져옵니다

내가 내 PDF 파일에서 벡터 그래픽을 사용할 수 있습니까?

아니요, 아니요, 오픈 소스 패키지는 this를 수행하지 않습니다. , PageCatcher는 (이전 대답을 참조) 쉽게 정확히 이미지 파일을 하듯이 그것을 사용 후 PDF로 을 절약하고 의해 모든 벡터 이미지를 통합 할 수 있으며, 보고서 마크 업 언어는 JPG와 함께 PDF 파일 을 받아 GIF 및 PNG.

업데이트 : 나는 잠시 동안이에 못 봤어하지만 on the page of pdfrw는 말한다 :

pdfrw 읽고 PDF 파일을 작성할 수 있습니다, 또한 어떤 수있는 PDF 파일을 읽어 올 수 있습니다 그런 다음 reportlab 내부에서 사용하십시오.

+0

맞습니다. pdfrw 페이지와 일부 [questions] (http://stackoverflow.com/questions/31712386/loading-matplotlib-object-into-reportlab/)에서이 두 가지에 대해 pdfrw를 사용하는 두 가지 예제가 있습니다. –

1

당신은 reportlab과 함께 멋진 pdfrw 패키지를 사용하고 직접 유동성으로하기 matplotlib 수치의 파일 - 류의 객체를 전달하는 데 사용할 수 있습니다 :이 전에 대답했다

, 그러나 나는 최소한의 예를주고 싶어 여기, 여기 찾아보세요 : 당신은하기 matplotlib에서 SVG 수출을 사용하고 reportlab PDF 파일을 생성에서 벡터 그래픽을 포함하는 svglib 파이썬 라이브러리를 사용할 수 있습니다 https://stackoverflow.com/a/13870512/4497962

from io import BytesIO 
import matplotlib.pyplot as plt 
from pdfrw import PdfReader, PdfDict 
from pdfrw.buildxobj import pagexobj 
from pdfrw.toreportlab import makerl 
from reportlab.platypus import Flowable 
from reportlab.lib.enums import TA_JUSTIFY,TA_LEFT,TA_CENTER,TA_RIGHT 

class PdfImage(Flowable): 
    """ 
    PdfImage wraps the first page from a PDF file as a Flowable 
    which can be included into a ReportLab Platypus document. 
    Based on the vectorpdf extension in rst2pdf (http://code.google.com/p/rst2pdf/) 

    This can be used from the place where you want to return your matplotlib image 
    as a Flowable: 

     img = BytesIO() 

     fig, ax = plt.subplots(figsize=(canvaswidth,canvaswidth)) 

     ax.plot([1,2,3],[6,5,4],antialiased=True,linewidth=2,color='red',label='a curve') 

     fig.savefig(img,format='PDF') 

     return(PdfImage(img)) 

    """ 

    def __init__(self, filename_or_object, width=None, height=None, kind='direct'): 
     # If using StringIO buffer, set pointer to begining 
     if hasattr(filename_or_object, 'read'): 
      filename_or_object.seek(0) 
      #print("read") 
     self.page = PdfReader(filename_or_object, decompress=False).pages[0] 
     self.xobj = pagexobj(self.page) 

     self.imageWidth = width 
     self.imageHeight = height 
     x1, y1, x2, y2 = self.xobj.BBox 

     self._w, self._h = x2 - x1, y2 - y1 
     if not self.imageWidth: 
      self.imageWidth = self._w 
     if not self.imageHeight: 
      self.imageHeight = self._h 
     self.__ratio = float(self.imageWidth)/self.imageHeight 
     if kind in ['direct','absolute'] or width==None or height==None: 
      self.drawWidth = width or self.imageWidth 
      self.drawHeight = height or self.imageHeight 
     elif kind in ['bound','proportional']: 
      factor = min(float(width)/self._w,float(height)/self._h) 
      self.drawWidth = self._w*factor 
      self.drawHeight = self._h*factor 

    def wrap(self, availableWidth, availableHeight): 
     """ 
     returns draw- width and height 

     convenience function to adapt your image 
     to the available Space that is available 
     """ 
     return self.drawWidth, self.drawHeight 

    def drawOn(self, canv, x, y, _sW=0): 
     """ 
     translates Bounding Box and scales the given canvas 
     """ 
     if _sW > 0 and hasattr(self, 'hAlign'): 
      a = self.hAlign 
      if a in ('CENTER', 'CENTRE', TA_CENTER): 
       x += 0.5*_sW 
      elif a in ('RIGHT', TA_RIGHT): 
       x += _sW 
      elif a not in ('LEFT', TA_LEFT): 
       raise ValueError("Bad hAlign value " + str(a)) 

     #xobj_name = makerl(canv._doc, self.xobj) 
     xobj_name = makerl(canv, self.xobj) 

     xscale = self.drawWidth/self._w 
     yscale = self.drawHeight/self._h 

     x -= self.xobj.BBox[0] * xscale 
     y -= self.xobj.BBox[1] * yscale 

     canv.saveState() 
     canv.translate(x, y) 
     canv.scale(xscale, yscale) 
     canv.doForm(xobj_name) 
     canv.restoreState() 
+0

내가 필요한 것! 코드를 보내 주셔서 감사합니다! – desa

+0

당신이 이것을 원한다면 다음을 참고하십시오 : https://pypi.python.org/pypi/autobasedoc/ – skidzo

1

. svglib은 svg 파일을 가져 와서 reportlab에서 직접 사용할 수있는 그리기 개체를 만듭니다.

은 자세한 내용은이 질문을 참조 : Generating PDFs from SVG input

관련 문제