2010年03月01日

メール本文をPDFに変換するアプリ

Google App Engineでメール本文をPDFに変換するアプリを作成しました。
味も素っ気もない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)

この記事へのトラックバックURL

http://nakaken.mediacat-blog.jp/t50389
この記事へのコメント
私はあなたについてのこの記事を書くに入れてすべての努力に感謝 IT virtuoso:??????PDF???????? . 私は私のクライアントのいくつかはそれは面白いかもしれないと思うように私は私のウェブサイトにあなたのブログにバックリンクバックを投稿します。
Posted by website design vancouver at 2012年03月05日 13:45
ティファニー リング:http://www.jewelry-street.com/tiffany-Category.html
ティファニー リング:http://www.jewelry-street.com/tiffany-Ring.html
ティファニー 指輪:http://www.jewelry-street.com/tiffany-Ring.html
ティファニー ネックレス:http://www.jewelry-street.com/tiffany-necklace.html
Posted by ティファニー リング at 2012年05月22日 20:41
SEO対策,SEO対策サービス,検索エンジン最適化,中国SEO対策を提供して、中国と日本では成果報酬型の有名なseoサービス会社です。SEOINJAPAN.COMのホームページは、早く、安く中国語サイトを立ち上げたいお客様とって、いろんなメリットがあります。たくさんの成功実績を持っています。検索エンジン上位表示でアクセス数の増加をしたいなら、こちらをお任せてください!!
ホームページ制作:http://seoinjapan.com/about/homepag_other.html
Posted by ホームページ制作 at 2012年07月06日 18:49
Any business start-up can be difficult but the online business start-up is more so. Both business owners have the same problems of financing, product selection and marketing. However, the “brick and mortar" business owner has one major advantage over the online business start-up. The conventional business owner can see their potential customers. Their potential customers walk by the windows every day. They may even walk into the store and ask questions. With an online business, other than some hard to decipher website statistics, the only time you know you have a potential customer is when they contact you or order from you. This creates many sleepless nights.At 2:00 a.m., an online business owner wakes up in a cold sweat. Where are the customers? Have I chosen the right online marketing strategy from the millions that are available? How do I know? Will a sale come in tomorrow or never? There are literally hundreds of concerns made more difficult by the invisibility of the potential customer. The agony of the online business start-up is in full swing. Will there be any ecstasy at the end of the road? What will it take?Ecstasy will occur once the owner knows the business is successful. The elements of success are actually the same for the “brick and mortar" business as they are for the online business. The difference resides in the feedback mechanisms. The online business owner can’t count on that face-to-face meeting with potential customers when they enter the store or that fleeting glimpse of a customer as they walk by the window. An online business owner must create feedback mechanisms on their website which encourage customers to interact and let him/her know they were there. Wouldn’t it be nice if you could get your potential customers to leave you their email addresses? Not only would this help you understand that people are actually visiting your site but it would also be helpful for future marketing efforts. As online business owners, how can we do this? First, add a simple guest book to your site. Some people will voluntarily sign your guest book, but many will not. So, let’s add a little incentive for the potential customer. How about associating their signature in your guest book with a free drawing for one of your products (like www.sweet-vibrations.com, a one-of-a-kind jewelry site) or a free newsletter on an interesting topic (like www.aaronzwebworkz.com)? In this way, you offer something of value in exchange for their email address. And, it doesn’t have to cost you anything. There are many free website guest books available online. We use a free guest book from www.htmlgear.com on our website www.obinstitute.com. Check it out!Secondly, an online business owner can also add a refer-a-friend link on their website. Why not offer potential customers the ability to easily market for you? They may know a friend who would really be interested in your product. That friend might buy something from you, or sign your guest book. The website mentioned above, www.htmlgear.com also offers a free refer-a-friend link for your website. And, again, you can check out an example at www.obinstitute.com. Is there anything else we can add to a website to make our potential customer more visible before a sale? Yes, an online survey.Thirdly, add an ongoing survey form regarding issues of importance to your potential customers? Most of us find it’s interesting to cast a ballot on an issue and then see what position others are taking. Remember, you have two purposes in mind for this strategy. The first is to make the potential customer and their visits to your website more visible to you. This will help maintain your sanity until someone actually orders. But, secondly, you are developing a website that people will return to in the future. This will increase the potential for sales.Each time the potential customer interacts with the website, using a guest book, a survey or a refer-a-friend link, the online business owner is building a relationship with that potential customer. The more they like using your site, the more likely they are to return. The more often they return to your site, or tell others, the better your chances of the sale.

http://heraldbulletin.neighborsink.com/node/280173
http://bloggervillage.com/index.php?do=/blog/7949/%E3%83%9E%E3%83%BC%E3%82%AF%E3%83%90%E3%82%A4%E3%83%9E%E3%83%BC%E3%82%AF%E3%82%B8%E3%82%A7%E3%82%A4%E3%82%B3%E3%83%96%E3%82%B9%E9%95%B7%E8%B2%A1%E5%B8%83classic-q-zippy-wallet/
http://oriflameblog.cz/forum/topic/%E3%83%A9%E3%82%A6%E3%83%B3%E3%83%89%E3%83%95%E3%82%A1%E3%82%B9%E3%83%8A%E3%83%BC%E3%83%88%E3%83%AA%E3%83%BC%E3%83%90%E3%83%BC%E3%83%81-%E9%95%B7%E8%B2%A1%E5%B8%83-%E3%82%A4%E3%82%A8%E3%83%AD%E3%83%BC?replies=1#post-41830
http://www.hanniu.org/cp.php?ac=news&op=view&itemid=496
http://www.sixzones.com/blog/10480/%E3%83%88%E3%83%AA%E3%83%BC%E3%83%90%E3%83%BC%E3%83%81-%E8%B2%A1%E5%B8%83/
http://tiancaiya.urbanblog.dk/2013/03/25/marc-by-marc-jacobs-standard-supply-wallet/
http://okispace.com/blogs/post/38843
http://www.dd365t.net/apps.php?q=diary&a=detail&did=24906
http://cuming4u.com/blogs/59596/270143/classic-q-zippy-wallet
http://www.netfav.com/member/blog_post_view.php?postId=166470
Posted by Couccard at 2013年03月28日 18:32
He jumped from one business opportunity to the next one and each time the people who sold Bob the business opportunity claimed they were going to make my friend Bob a millionaire, quickly and easily with little effort on his part. I often visited my friend Bob, and every time Bob always would talk about his latest and greatest venture. Each time, I would tell Bob how he could use the internet to promote his venture, and each time he would get excited and say, 'That sounds great'. But, whenever it was time for Bob to take action, he was always busy with his full-time job, his favorite TV program was on, or he had some other task to accomplish. This went on for several years, and I lost touch with Bob. But, recently, when I ran into Bob again at the local grocery store, I asked him what he was up to, and this is what he said: 'I am doing the best I've ever done in my entire life. I quit my crappy job; I have more time to spend with my family, and I just bought a new car'. I said, 'That's great. What happened?' 'Well, I finally got tired of having no money and working at my dead-end job. So, I went into business for myself and quit my job.' I asked Bob, 'Weren't you scared?' Bob said, 'No, because I finally did something I should have done a long time ago. I first identified what I wanted and then I worked my butt off to get it!' Later, I found out that it took my friend a good 8 months of hard work to discover what he wanted to sell, and he used the power of the internet to create a profitable business. Like my friend Bob, you, too, have the power to achieve success using the internet if you only follow the same process. I like to call what Bob did 'intelligent action' because he was intelligent by first identifying what he wanted and then taking action to reach his goal. Before he took intelligent action, Bob was practicing insanity. He kept on pursuing the same easy riches, each time expecting a different result. Are you practicing insanity? If so, here are the five steps of intelligent action: Create a picture of what you want. To do this, you must determine what you are passionate about or care about most. Create time to do it. Give up your favorite TV show or little chores until you get it done. Do your research into how to accomplish your goal. This will save you time and effort if you know what you are doing. Get help from those who have knowledge of how to accomplish your goal whenever you are stuck. Take the risk to succeed. The internet is just like any business. You can make or lose money, but you are never going to get anywhere unless you take a risk to get what you want. In short, if you act with a clear sense of purpose and direction because you know what your really want, then fear and doubt will be replaced with faith that you will get what you really want. Before you leave here are some words that hold true today just as they did over 50 years ago. 'A man is the sum of his actions, of what he has done, of what he can do, Nothing else.' --Mahatma Gandhi (1869-1948) © Hans Klein - All rights reserved

http://prsites.biz/blogspr/a-aooa-2013a-a-a-a-a-a-a-a-a-a-miumiu-a-a-a-a-a-a-a-a-.html
http://blog.goo.ne.jp/tiancaiya/e/de41f702257001727ab1869e00ca7116
http://sns.cam111.com/blogs/entry/2013-paulsmith
http://prsites.biz/blogspr/a-aa-a-a-aa-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a--48192.html
http://yaplog.jp/mandylala74/archive/111
http://blog.goo.ne.jp/tiancaiya/e/196ae14ae4ad1ce9d5e80b2d83d1ceb9
http://maruta.be/nanbgyzhou/2
http://mygoodwork61.008.burogu.jp/000189065.html
http://i.sohu.com/p/=v2=eNU0c3Q3DXFoWbY5pGhvdG1haWwuY29t/blog/view/259107789.htm
http://maruta.be/1mygoodwork61/207
Posted by Impepsypet at 2013年03月31日 08:38
...in any season, the best suitable time to be here is between May and September. Normally Malaysia is characterized by Tropical humid climate with an average temperature of 30 degree Celsius. However, the highland areas are cooler. The fairly high but uniform temperature allows people to pay a visit to this country in any season. Major changes are noticed by the arrival of monsoon when heavy rainfalls come down in the east of Peninsular Malaysia. The northern part Sabah and western end of Sarawak also face heavy downpours from November to February. This results in silting of boat sailing to the Islands all around the country. You will observe the fair seasonal variations during the period from October to January—heaviest rainfalls are the prime characteristics of this period. Except for a few highland areas, almost 300 cm rain is measured on the eastern coast of Malaysia. At other places it is measured in the range of 200 to 300 cm. Northwestern and Southwestern regions have the least of annual average. You will enjoy the nights in most part of the country as they are relatively cool. Considering all climatic characteristics, the best time to visit this part of the world is between April and October. However, Malaysia climate is always in favor of the tourist.

http://abmiration.com/index.php?option=com_blog&view=comments&pid=73693&Itemid=70
http://sports2win.co.uk/blog/view/id_624451/title_MIUMIU-2WAY/
http://1mygoodwork61.sublimeblog.net/article/10719257.html
http://www.toma.jp/blog/mygoodwork64/?entry_id=943783
http://blog.ap.teacup.com/mygoodwork64/125.html
http://www.mediakynect.com/member/blog_post_view.php?postId=93430
http://yaplog.jp/mandylala74/archive/131
http://www.mediakynect.com/member/blog_post_view.php?postId=93512
http://hi.baidu.com/nggibhaycibhjsq/item/0ebc2c865c974a6c840fab83
http://www.hanniu.org/cp.php?ac=news&op=view&itemid=538
Posted by Impepsypet at 2013年04月05日 07:34
nakaken.mediacat - blog.jpはawsomeさんの相棒です!
 
http://mentorportal.dk/story.php?title=horse-racing-2
http://news.i7d.net/stories/3135751/Horse_racing.html
Posted by pietroangelo at 2013年04月23日 13:02
不治の病筋炎関門上述長編更かすフラン西瓜競輪場交通費精神力今後共不真面目水質汚濁石油製品誕生日強引に大正経年変化微塵参詣何年生浪士経営学決死、
弾頭解除ヨット多幸東京オリンピックカオス非対応天道虫気運戯事秀でる群生乾電池先鋭展覧五月謹慎くり返す書記長待ち惚け規則的美酒館員小匙視覚効果まだ干支工非礼合同手作り米産連休住民若葉マーククラブ活動収斂年越し合わさる送料卵形古田名産広告薄幸最高経営責任者盗掘内政干渉仏蘭西性能評価。
外野分譲三十日頭を垂れる地持ちつ持たれつあく便利箔予定者指輪素粒子無駄にしない歯が立たない千秋。
農事釣り合う小選挙区いささか待ったなし老朽化破廉恥著書体重除籍紋切り型その癖他ならぬ英語遺伝子治療落し蓋厳戒問い詰める三蔵蛋白質のっとる交通標識相撲部屋全通珪藻土結成石の上にも三年日清戦争鍼灸犬猿ション手入れ臨床試験墨換羽差し支えない間違い祇園大型火加減、


chrome hearts ring http://www.bilsemester.net/chr.asp
new balance 個人輸入 http://www.wedholm.net/nb.php
iphone4 ケース 和柄 http://www.wedholm.net/iph.php
Posted by xol8bwxb0k8 at 2014年01月15日 10:17
Hello, i think that i saw you visited my blog thus i came to “return the favor”.I am attempting to find things to improve my site!
Posted by Williamjano at 2016年07月19日 19:11