How to use Foxit PDF SDK in a Web application’s server side
In this tutorial, you’ll learn how to use Foxit PDF SDK in a Web application’s server side. Foxit PDF SDK supports Python, C#, and Java language for Web server development. The example in the current tutorial uses Python language to develop a simple web application demo.
Contents
Preparation for Web application
Install a version of Python in which Foxit PDF SDK is supported. The example in this article uses Python 3.8 on Windows.
Python virtual environment
1. Create a python viratual environment.
mkdir webappdemo
cd webappdemo
python -m venv .venv
2. Activate the environment.
.venv\Scripts\activate
3. Install Foxit PDF SDK and Third-party modules.
In this example, we used Flask, which is a lightweight web application framework based on Python. In the activated virtual environment, perform the following actions:
pip install FoxitPDFSDKPython3
pip install Flask
Rending a PDF Page by using Foxit PDF SDK
Create a python script file named app_demo.py.
1. Importing Python modules and libraries.
# Description: This is a demo for Foxit PDF SDK for Python.
import io
# import flask class
from flask import Flask
from flask import send_file
# import Foxit PDF SDK for python
from FoxitPDFSDKPython3 import *
2. Create Flask app.
app = Flask(__name__)
3. Initialize SDK library.
def InitLibrary():
# The parameter "sn" can be found in the "gsdk_sn.txt" (the string after "SN=") and the "key" can be found in the "gsdk_key.txt" (the string after "Sign=").
sn = ""
key = ""
# Initialize library
error_code = Library.Initialize(sn, key)
if error_code != e_ErrSuccess:
print("Library Initialize Error: {}".format(error_code))
return False
print("Library Initialize Success")
return True
# Initialize library
is_library_init = InitLibrary()
4. Define MemoryStream callback class.
class MemoryStream(StreamCallback):
def __init__(self, *args):
super().__init__()
self.buffer_ = bytearray(b'')
self.ref_ = 0
def __del__(self):
self.__disown__()
def Retain(self, *args):
self.ref_ += 1
return self
def IsEOF(self, *args):
return True
def GetPosition(self, *args):
pass
def Release(self, *args):
self.ref_ -= 1
def GetSize(self, *args):
pass
def Flush(self, *args):
return True
def ReadBlock(self, *args):
pass
def WriteBlock(self, *args):
if args[0] is not None:
self.buffer_[args[0][1]:args[0][1]] = bytearray(args[0][0])
return True
else:
return False
5. Rending a PDF page.
def WebDemo():
path = "D:/AboutFoxit.pdf"
# Load the document
doc = PDFDoc(path)
if e_ErrSuccess != doc.Load(""):
return None
page_count = doc.GetPageCount()
print("Page Count: {}".format(page_count))
page = doc.GetPage(0)
# Parse the page
page.StartParse(PDFPage.e_ParsePageNormal, None, False)
# Prepare a bitmap for rendering.
page_width = page.GetWidth()
page_height = page.GetHeight()
width = int(page_width)
height = int(page_height)
rectf = RectF(0.5, 0.5, width, height)
bitmap_width = int(rectf.Width())
bitmap_height = int(rectf.Height())
bitmap = Bitmap(bitmap_width, bitmap_height, Bitmap.e_DIBArgb)
render = Renderer(bitmap, False)
matrix = page.GetDisplayMatrix(0, 0, width, height, 0)
bitmap.FillRect(0xFFFFFFFF, None)
# render page to bitmap
render.StartRender(page, matrix, None)
image = Image()
image.AddFrame(bitmap)
stream = MemoryStream()
# save bitmap to stream
image.SaveAs(stream, ".png")
# return image buffer
return stream.buffer_
6. Release SDK library.
@app.teardown_appcontext
def teardown_appcontext(exception):
print("teardown_appcontext")
Library.Release()
7. Add Flask routing mapping.
# @app.route("/") maps the root path ("/") to the web_demo function
@app.route("/")
def web_demo():
if not is_library_init:
return "<p>Library Initialize Error</p>"
image_buff = WebDemo()
if image_buff is not None:
image_io = io.BytesIO(image_buff)
image_io.seek(0)
return send_file(image_io, mimetype='image/png')
else:
return "<p>Error</p>"
Start Web Application server
Starting the service requires ensuring that it is under the creation of a Python virtual environment.
cd webappdemo
flask --app app_demo run
Open http://127.0.0.1:5000 in your browser to access the web app demo and the window is shown as follows.
Updated on October 16, 2023