LoginSignup
2
2

More than 5 years have passed since last update.

AWS Lambda で JSONを受け取って新しいページにPDFを吐く

Posted at

なんだこれ……。「限定共有投稿」に黒魔術が残っていたので晒す。


# -*- coding:utf-8 -*-
import BaseHTTPServer
import json

class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):

    def do_GET(self):
        if self.path.endswith('favicon.ico'):
            return

        self.send_response(200)
        self.end_headers()
        self.wfile.write(index_handler());
        return

    def do_POST(self):
        self.send_response(200)
        content_len = int(self.headers.get('content-length'))
        requestBody = json.loads(self.rfile.read(content_len))
        if self.path.endswith('my.pdf'):
            self.send_header("content-type", "application/pdf")
            self.end_headers()
            self.wfile.write(lambda_handler(requestBody, {}))
        return

def lambda_handler(data, context):
    return """%%PDF-1.4
1 0 obj
<</Pages 2 0 R/Type /Catalog>>
endobj
2 0 obj
<</Kids [3 0 R]/Count 1/Type/Pages>>
endobj
3 0 obj
<</Contents 5 0 R/Parent 2 0 R/MediaBox[0 0 612 292]/Resources<</Font<</F1 4 0 R >>/ProcSet[/PDF/Text]>>/Type/Page>>
endobj
4 0 obj
<</Type/Font/Subtype/Type1/Name/F1/BaseFont/Helvetica/Encoding/MacRomanEncoding>>
endobj
5 0 obj
<</Length 73 >> stream
BT /F1 24 Tf 30 100 Td (%s) Tj ET
endstream
endobj
xref
0 7
0000000000 65535 f
0000000010 00000 n
0000000059 00000 n
0000000114 00000 n
0000000249 00000 n
0000000349 00000 n
trailer << /Size 7 /Root 1 0 R >>
startxref
%d
%%%%EOF""" % (data['message'], 433+len(data['message']))

def index_handler():
    return """<!DOCTYPE html>
<html>
<head>
  <title>a</title>
  <style>
    div, embed { width: 100%; height: 125vw; }
  </style>
</head>
<body>
  <button id="b1">view pdf</button>
  <div id="d1"></div>
  <script>
  (function() {
    document.getElementById("b1").addEventListener("click", function() {
      // ブロックされないようにclickハンドラ内でオープンしとく
      var previewWindow = window.open("", "preview");
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
        if(xhr.readyState === 4 && xhr.status === 200){
          var url = URL.createObjectURL(this.response);
          if(window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(this.response, 'my.pdf');
          } else {
            // オープンしといた別Windowで表示
            previewWindow.location.href = url;
            // 埋め込んじゃうというのも
            document.getElementById("d1").innerHTML = 
              '<embed type="application/pdf" src="' + url + '"></embed>';
          }
        }
      };
      // JSON形式でポストして結果はblobで受け取る
      window.setTimeout(function() {
        xhr.open("POST", "my.pdf");
        xhr.responseType = "blob";
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.send('{"message":"Hello!!"}');
      }, 1000);
    });
  })();
  </script>
</body>
</html>"""

if __name__ == '__main__':
    server_address = ('', 8080)
    httpd = BaseHTTPServer.HTTPServer(server_address, MyHandler)
    httpd.serve_forever()

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2