味も素っ気もないWebページはこちら。
http://nakakenstudy.appspot.com/
このページは本質的には全然関係なくて利用に当たっては、mail2pdf@nakakenstudy.appspotmail.comまでメールを送ってください。メールの本文がPDFとなって返信されます。
PDFの変換を試すには、http://nakakenstudy.appspot.com/post2pdf をリクエストしてください。
今回はreportlabを使ってテキストをPDFに変換しました。といってもベタにテキストにするだけなので、ほとんど実装していません。あんまり短くできたので、記念にソース公開しておきます。うるさい事言わないので、勝手にコピペしてください。blogの制約上全角スペースでインデントをつけているので、各自で半角スペースに変換しておいてください。
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import logging
import StringIO
import pdf
from email.utils import parseaddr
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp.mail_handlers import *
SENDER_ADDRESS = 'nakaken@mediacat.ne.jp'
def main():
application = webapp.WSGIApplication([
(r'/', MainHandler),
(r'/_ah/mail/.+', Mail2PdfHandler),
(r'/post2pdf', Post2PdfHandler),
], debug=True)
util.run_wsgi_app(application)
def goodDecode(encodedPayload):
encoding = encodedPayload.encoding
payload = encodedPayload.payload
logging.debug(encoding)
logging.debug(payload)
if encoding and encoding.lower() != '7bit':
payload = payload.decode(encoding)
else:
try:
payload = payload.decode('ISO-2022-JP')
except Exception, value:
logging.warn(value)
return payload
class MainHandler(webapp.RequestHandler):
def get(self):
self.response.out.write('Mail to "mail2pdf at nakakenstudy.appspotmail.com" and you can get pdf file converted from your mail.')
class Mail2PdfHandler(InboundMailHandler):
def receive(self, message):
logging.info('do Mail2PdfHandler.receive')
editormail = parseaddr(message.to)[1]
account = editormail.split('@')[0]
if account != 'mail2pdf':
logging.warn(account + ' is an undefined account.')
return
content = ''
for body in message.bodies(content_type='text/plain'):
content += goodDecode(body[1])
logging.debug(content)
buffer = StringIO.StringIO()
pdf.go(buffer, content)
pdffile = buffer.getvalue()
buffer.close()
logging.info('sender=' + SENDER_ADDRESS)
logging.info('to=' + message.sender)
mail.send_mail(
sender=SENDER_ADDRESS,
to=message.sender,
subject='result of converted pdf from mail',
body='Here is the pdf file you want, yeah!',
attachments=[('content.pdf', pdffile)],
)
class Post2PdfHandler(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/html'
self.response.out.write("""<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<form action="/post2pdf" method="post">
<p>PDFに変換したい文字列を入力してください</p>
<textarea cols="60" rows="30" name="content"></textarea><br />
<input type="submit" value="変換" />
</form>
</body>
</html>"""
)
def post(self):
content = self.request.get('content')
buffer = self.response.out
pdf.go(buffer, content)
self.response.headers['Content-Type'] = 'application/pdf'
if __name__ == '__main__':
main()
[[ pdf.py ]]
# -*- coding: utf-8 -*-
import cgi
import StringIO
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
from reportlab.platypus import SimpleDocTemplate, Spacer, XPreformatted
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
from reportlab.lib.units import inch
pdfmetrics.registerFont(TTFont('Togoshi-mono', 'togoshi-mono.ttf'))
PAGE_HEIGHT=defaultPageSize[1]
PAGE_WIDTH=defaultPageSize[0]
styles = getSampleStyleSheet()
my_style = styles["Normal"]
my_style.name = "bonlife"
my_style.fontName = "Togoshi-mono"
my_style.fontSize = 0.15*inch
my_style.leading = 11
def go(filename, content):
doc = SimpleDocTemplate(filename)
Story = [Spacer(1, 0.5*inch)]
style = my_style
x = XPreformatted(cgi.escape(content), style)
Story.append(x)
doc.build(Story)
0 件のコメント:
コメントを投稿