2012-03-24 2 views
2

URL의 HTML 소스를 가져 와서 구문 분석 한 다음 결과를 PDF로 인쇄하려고합니다.Python - URL 가져 오기, 구문 분석 및 PDF 인쇄

나는 BeautifulSoup, urllib2 및 reportlab에 의존하고 싶었지만 제대로 결합하는 방법이 부족합니다.

오류로 django 1.3.1 dev 서버를 실행하고보기에 액세스 할 때 'module' object is not callable이 표시됩니다.

다음
from reportlab.pdfgen import canvas 
from cStringIO import StringIO 
from django.http import HttpResponse 
from django.shortcuts import render_to_response 
from django.template import RequestContext 
# Fetching the URL 
import urllib2 

# Parsing the HTML 
from BeautifulSoup import BeautifulSoup 

# The ConverterForm 
from django import forms 

class ConverterForm(forms.Form): 
    # Use textarea instead the default TextInput. 
    html_files = forms.CharField(widget=forms.Textarea) 
    filename = forms.CharField() 

# Create your views here. 
def create_pdf(request): 
    # If the form has been submitted 
    if request.method == 'POST': 
     # A form bound to the POST data 
     form = ConverterForm(request.POST) 
    # All validation rules pass 
    if form.is_valid(): 
     # PDF creation process 
     # Assign variables 
     html_files = form.cleaned_data['html_files'] 
     filename = form.cleaned_data['filename'] 

     # Create the HttpResponse object with the appropriate PDF headers. 
     response = HttpResponse(mimetype='application/pdf') 
     # The use of attachment forces the Save as dialog to open. 
     response['Content-Disposition'] = 'attachment; filename=%s.pdf' % filename 

     buffer = StringIO() 

     # Get the page source 
     page = urllib2.urlopen(html_files) 
     html = page.read() 

     # Parse the page source 
     soup = BeautifulSoup(html) 

     # Create the PDF object, using the StringIO() object as its "file". 
     p = canvas.Canvas(buffer) 

     # Draw things on the PDF and generate the PDF. 
     # See ReportLab documentation for full list of functions. 
     p.drawString(100, 100, soup) 

     # Close the PDF object cleanly. 
     p.showPage() 
     p.save() 

     # Get the value of the StringIO buffer and write it to the response. 
     pdf = buffer.getvalue() 
     buffer.close() 
     response.write(pdf) 
     return response 

    else: 
     # An unbound form 
     form = ConverterForm() 

    # For RequestContext in relation to csrf see more here: 
    # https://docs.djangoproject.com/en/1.3/intro/tutorial04/ 
    return render_to_response('converter/index.html', { 
    'form': form, 
    }, context_instance=RequestContext(request)) 
+1

어디서 오류가 있습니까? 그것을 전부 보여주십시오. 전체 코드를 표시하지 않았습니다. – Marcin

+0

코드를 편집했습니다. 죄송합니다. 처음에 나머지는 관련이 없을 수도 있습니다. 감사합니다. – orschiro

+0

정확한 오류는'buffer = StringIO()'입니다. 이것은'buffer = StringIO.StringIO()'가되어야합니다. 그러나 나는 간단한 해결책을 답으로 제공했습니다. –

답변

1

이 간단한 방법입니다 :

import cStringIO as StringIO 

import ho.pisa as pisa 
import requests 

def pdf_maker(request): 

    browser = requests.get('http://www.google.com/') 
    html = browser.text 

    result = StringIO.StringIO() 
    source = StringIO.StringIO(html.encode('UTF-8')) # adjust as required 

    pdf = pisa.pisaDocument(source,dest=result) 

    if not pdf.err: 
     response = HttpResponse(result.getvalue(),mimetype='application/pdf') 
     response['Content-Disposition'] = 'attachment; filename=the_file.pdf' 
     return response 

    return render(request,'error.html') 

requestspisa 사용

내 코드입니다. 그러나, 당신은 이것 (그리고 다른 그런 해결책들)에 약간의 제한을 가질 것입니다. 즉, PDF 변환 프로세스가 인터넷에서 직접 이미지를로드 할 수 없으므로 직접 이미지를 가져와 삽입하는 방법을 찾아야합니다. 모듈과 클래스가 동일한 기본 이름을 가지고 있기 때문에 그것은 혼란 스러울 수

from BeautifulSoup import BeautifulSoup 

:

+1

감사합니다. 그러나 PyPi에 따르면 Pisa는 더 이상 개발되지 않았습니다. XHTML2PDF 라이브러리는 Pisa와 같은 방식으로 작동합니까? – orschiro

+0

예, 거의 똑같은 방식입니다. –

+0

그럼에도 불구하고 위의 방법이 실패하는 이유를 이해하고자합니다. – orschiro

4

당신은 BeautifulSoup 클래스를 가져와야합니다.

+0

분명히 내 시스템에 없습니다. 'converter.views를 가져올 수 없습니다. 오류 : 모듈 이름이 BeutifulSoup'입니다. 나는 ActivePython 배포판을 사용하고 pypm을 통해 beautifulsoup를 설치했다. http://code.activestate.com/pypm/beautifulsoup/ – orschiro

+2

@orschiro : 맞춤법을 검사하십시오. – jfs

+0

이것은 문제를 해결하지 못했습니다. 위의 코드를 업데이트했습니다. 정확한 오류 출력 : http://dpaste.com/721558/ – orschiro