Generate PDF documents with Python
Posted by admin
Creating Documents is universal truth across organizations. Every organization either big or small.
EDocGen is a powerful template-based automation tool that enables users to quickly and easily create automated documents using pre-built templates.
The platform's versatility enables the generation of documents in multiple formats such as PDF, DOCX, and more. The ability to send documents via email and download bulk documents from databases further increases its usefulness, making it a reliable solution for companies.
PHP is a popular server-side scripting language used widely for web development. One of the main advantages of using PHP for APIs is its simplicity and ease of use.
Therefore, it offers straightforward integration with existing workflows in PHP, making it an effortless addition to any business's document creation process.
In this article, we'll explore the features and benefits of the system for template-based document generation in PHP.
The system requires the use of a RESTful API to communicate with the platform and submit requests for document generation. While there are many RESTful clients available for PHP, one popular option for developers is the php-restclient library. i.e. https://github.com/tcdent/php-restclient
As a PHP developer, you may prefer to use an alternative RESTful client that you are more familiar with or that provides additional features or functionality that you require.
The document automation API streamlines document generation for developers, providing an efficient and straightforward solution with minimal coding. It offers support for multiple modes of document generation from several data sources. Thus, it addresses diverse document generation scenarios within an enterprise. In this section, we will provide a step-by-step guide for each use case.
To facilitate all API interactions, the API utilizes a JWT-based authentication token. To acquire this token, you must register and submit your login credentials to the /login endpoint. You will then be provided with an access token that must be included in every subsequent API call.
In PHP, we can do the following way:
function __construct()
{
// To get user-specific token
$ENV["EDOC_USERNAME"] = ""; //username
$ENV["EDOC_PASSWORD"] = ""; //password
$this->api = new RestClient(["base_url" => "https://app.eDocGen.com/"]);
$this->result = $this->api->post("login", [
"username" => $ENV["EDOC_USERNAME"],
"password" => $ENV["EDOC_PASSWORD"],
]);
$this->response = $this->result->decode_response();
# print_r($this->response);
}
```
This code defines a constructor method that initializes a new instance of the class. The purpose of this constructor is to retrieve an access token for authentication with the API.
The API call to the login endpoint is then made using the post() method of the RestClient object. The login endpoint requires the username and password parameters to be included in the API call. These parameters are passed as an array in the second argument of the post() method.
Finally, the response from the API call is decoded and stored in the $this->response variable.
In the following steps, we will utilize this variable for generating various types of documents.
The template preparation section is an important part of the document generation process. A template acts as a blueprint or layout for the generated document, providing a consistent structure for the data to be populated into.
The system supports the use of various document formats such as PDF, HTML, and DOCX as input templates.
For example, in the provided template, the {Enter_Name} and {Enter_Email} tags are dynamic and will be replaced with appropriate data.
Once the templates are prepared, they can be used to generate documents either on-demand or in bulk, saving time and increasing efficiency in document creation.
After creating the template, it can be uploaded using either of the two options:
It provides the following API which can be used to upload the template file to the system server.
This API accepts a single parameter of type "formData" called "documentFile". This parameter represents the file to be uploaded as the template.
After uploading our template, we can obtain the corresponding template ID. This ID can be utilized to execute different API functions related to that specific template.
The API offers the capability to retrieve the template ID.
In PHP, we can do using following method:
```
public function getTemplateIdviaFileName($fileName)
{
if ($this->result->info->http_code == 200) {
$curl = curl_init();
$key = $this->response->token;
curl_setopt_array($curl, [
CURLOPT_URL =>
"https://app.eDocGen.com/api/v1/document/?search_column=filename&search_value=" .
rawurlencode($fileName),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => ["x-access-token: $key"],
]);
$response = curl_exec($curl);
curl_close($curl);
$arr = json_decode($response, true);
echo "Template ID's with file name - $fileName is : \n";
foreach ($arr["documents"] as $key => $value) {
print_r($value["_id"]);
echo "\n";
}
}
}
```
This PHP function leverages cURL to retrieve the template ID of a document from the system, utilizing the provided filename as the search parameter. The function includes authentication bypassing the access token in the x-access-token header and outputs a list of template IDs that correspond to the given filename.
The system supports generation of multiple documents with a single API call. This feature simplifies the process of creating professional, customized documents in bulk and saves time.
In order to utilize the Bulk Generate Document feature, the user must initially upload the document template to the server. The template is accepted in a variety of formats, including JSON, XLSX, and XML as previously mentioned.
Once the template is uploaded, the user can use the /api/v1/document/generate/bulk endpoint to generate multiple documents with a single API call.
It has mainly two modes:
Synchronous Generation is useful when generating documents using a single record. In this mode, the output is generated synchronously, immediately after the API call.
Asynchronous Generation is useful when generating documents using multiple records. The API automatically compresses the generated documents into a .zip file, simplifying the download and management of the output big files.
To use Bulk Generate Document with the API using PHP, the user needs to send a POST request to the /api/v1/document/generate/bulk endpoint with the necessary parameters.
These parameters include the template ID, data source, and mode of document generation. The data source can be a CSV file, a JSON array, or an XML file. The API processes the data source to generate the corresponding documents, which can be downloaded by the user.
```
public function downloadBulkUsingJson()
{
if ($this->result->info->http_code == 200) {
/*
These variable need to be adjusted as per requirement:
$format = "pdf"; // contains output format
$downloadedFileExt = ".zip"; // download fileout output format. Incase of bulk this will be .zip always
$documentId = "62f063426844520f75344091"; // documentID or TemplateId of document
$MAX_RETRY = 50; //Max number of retries to wait for download. Default 50.
$jsonFilePath = "/Users/Documents/TempWork/project/services/JSON_Data.json"; //path of json file to load
*/
// Start of customizing variables enter here
$format = "pdf";
$downloadedFileExt = ".zip";
$documentId = "62f063426844520f75344091";
$MAX_RETRY = 50;
$jsonFilePath = "/Users/JSON_Data.json";
//End
$curl = curl_init();
$fileName = strtoupper(bin2hex(openssl_random_pseudo_bytes(16)));
$key = $this->response->token;
echo $key . "\n";
// echo $fileName . "\n";
$data = [
"inputFile" => new CURLFILE(
$jsonFilePath
),
"documentId" => $documentId,
"format" => "pdf",
"outputFileName" => $fileName,
];
$inp = [
CURLOPT_URL => "https://app.eDocGen.com/api/v1/document/generate/bulk",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => ["x-access-token: $key"],
];
curl_setopt_array($curl, $inp);
$response = curl_exec($curl);
curl_close($curl);
echo $response;
if ($response === false) {
print "Could not make successful request\n";
return;
} else {
$response = json_decode($response);
}
$arr = $this->checkOutputGenerated($fileName, $format, $downloadedFileExt);
$retry = 0;
while (
is_null($arr["output"][0]["_id"]) != null &&
$retry < $MAX_RETRY
) {
echo 'Retrying Again.... \n';
echo $retry;
$arr = $this->checkOutputGenerated($fileName, $format, $downloadedFileExt);
$retry++;
}
if (is_null($arr["output"][0]["_id"])) {
echo 'Error !!! Cannot generate output after several retries \n';
return "";
} else {
$output_id = $arr["output"][0]["_id"];
$this->downloadOutput($output_id, $fileName, $downloadedFileExt);
}
}
}
```
In this code, we have a function named 'downloadBulkJson' that generates and downloads documents.
Firstly, the function opens an input JSON file and stores its contents in a variable. If the data contains more than one item, the function sets the 'generated_format' variable to 'zip', which compresses the generated documents into a .zip file.
On the other hand, if there is only one document, it is downloaded without any compression.
After that, we send a POST request to the /api/v1/document/generate/bulk endpoint along with the necessary parameters like input file, output file name, and format. Once the output file is generated, the function downloads and saves it to the local file system using a file name based on the unique generated file UUID.
The system allows users to generate bulk documents from a database using its API. This functionality is useful for users who want to generate documents based on a large number of records in their database.
```
public function downloadBulkUsingDB()
{
if ($this->result->info->http_code == 200) {
/*
These variables need to be adjusted as per requirement:
$format = "pdf"; //output format of document to be generated
$dbUrl ="jdbc:mysql://[email protected]:3306/sql6511576/sdtest"; // MySql DB URL
$dbPassword = "u8M7IYAq7a"; //db password
$dbQuery = "select * from sdtest"; //db query
$dbLimit = "100"; //Number of db entries to be fetched
$zip = ".zip"; //Downloaded file format. bydefault only .zip is supported
$MAX_RETRY = 50; //Max number of tries to download file
$documentId = "62f063426844520f75344091"; //Template id
// Start of customizing variables
$format = "pdf";
$dbVendor = "mysql";
$dbUrl ="jdbc:mysql://[email protected]:3306/sql6511576/sdtest";
$dbPassword = "u8M7IYAq7a";
$dbQuery = "select * from sdtest";
$dbLimit = "100";
$downloadedFileExt = ".zip";
$MAX_RETRY = 50;
$documentId = "62f063426844520f75344091";
$keyToFileName = "Prefix";
// end of variables
$curl = curl_init();
$fileName = strtoupper(bin2hex(openssl_random_pseudo_bytes(16)));
$key = $this->response->token;
echo $key . "\n";
echo $fileName . "\n";
$data = [
"dbVendor" => $dbVendor,
"dbUrl" => $dbUrl,
"dbLimit" => $dbLimit,
"dbPassword" => $dbPassword,
"dbQuery" => $dbQuery,
"documentId" => $documentId,
"format" => $format,
"outputFileName" => $fileName,
"keyToFileName" => $keyToFileName,
];
$inp = [
CURLOPT_URL => "https://app.eDocGen.com/api/v1/document/generate/bulk",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => ["x-access-token: $key"],
];
curl_setopt_array($curl, $inp);
$response = curl_exec($curl);
curl_close($curl);
echo $response;
if ($response === false) {
print "Could not make successful request\n";
return;
} else {
$response = json_decode($response);
}
$arr = $this->checkOutputGenerated($fileName, $format, $downloadedFileExt);
$retry = 0;
while (
is_null($arr["output"][0]["_id"]) != null &&
$retry < $MAX_RETRY
) {
echo 'Retrying Again.... \n';
echo $retry;
$arr = $this->checkOutputGenerated($fileName, $format, $downloadedFileExt);
$retry++;
}
if (is_null($arr["output"][0]["_id"])) {
echo 'Error !!! Cannot generate output after several retries \n';
return "";
} else {
$output_id = $arr["output"][0]["_id"];
$this->downloadOutput($output_id, $fileName, $downloadedFileExt);
}
}
}
```
This is a PHP function called downloadBulkUsingDB(). The purpose of this function is to generate and download multiple documents in bulk from a database using the PHP PDF generation API. the function initializes a cURL session to send a POST request to the API endpoint /api/v1/document/generate/bulk. The data required for the request is stored in an array, which includes the customized variables mentioned earlier. The response from the API is then decoded from JSON to an array.
The function then calls the checkOutputGenerated() method to check if the output file has been generated. This method checks the API's /api/v1/output/{output_id} endpoint to see if the output file with the given file name and format has been generated. If the file has not yet been generated, the function retries the check until the output file is available or the maximum number of retries has been reached.
Once the output file is generated, the function calls the downloadOutput() method to download the file to the local file system. This method sends a GET request to the API's /api/v1/output/download/{output_id} endpoint to download the file with the given output ID. The downloaded file is saved to the local file system with a name based on the generated file UUID to ensure uniqueness.
The system provides the ability to send generated documents via email to specified recipients.
This functionality is useful for automating the delivery of generated documents such as invoices, reports, and contracts to clients and stakeholders.
The 'sendOutputToEmail' function can be used for this purpose.
```
public function sendOutputToEmail($outputId, $emailId)
{
$curl = curl_init();
$key = $this->response->token;
$data = [
"outId" => $outputId,
"emailId" => $emailId,
];
$postdata = json_encode($data);
curl_setopt_array($curl, [
CURLOPT_URL => "https://app.eDocGen.com/api/v1/output/email",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $postdata,
CURLOPT_HTTPHEADER => [
"x-access-token: $key",
"Content-Type: application/json",
],
]);
$response = curl_exec($curl);
curl_close($curl);
print_r($response);
}
```
The function takes two parameters: $outputId and $emailId. $outputId is the ID of the generated output file that needs to be sent via email, while $emailId is the email address of the recipient.
In conclusion, EDocGen is an excellent solution for businesses looking to automate their document generation process. By eliminating the need for manual input and reducing human error, it allows companies to streamline their workflows and focus on more essential tasks. The ability to generate documents in various formats, send them via email, and download bulk documents from a database makes it a versatile platform for companies to rely on.
The automation simplifies the document generation process, making it an essential tool for any business seeking to optimize its operations.
Posted by admin
Creating Documents is universal truth across organizations. Every organization either big or small.
Posted by admin
Integrate with the Azure SQL Server to generate PDF documents from existing templates.
Posted by admin
Generate PDF documents from existing templates and send them by email from .Net application.