POST /v1/barcode/generate
Attributes
Attributes are case-sensitive and should be inside JSON for POST request. for example: { "url": "https://example.com/file1.pdf" }
| Attribute | Type | Required | Default | Description |
callback | string | No | - | The callback URL (or Webhook) used to receive the POST data. see Webhooks & Callbacks. This is only applicable when async is set to true. |
name | string | No | - | File name for the generated output, the input must be in string format. |
expiration | integer | No | 60 | Set the expiration time for the output link in minutes. After this specified duration, any generated output file(s) will be automatically deleted from PDF.co Temporary Files Storage. The maximum duration for link expiration varies based on your current subscription plan. To store permanent input files (e.g. re-usable images, pdf templates, documents) consider using PDF.co Built-In Files Storage. |
inline | boolean | No | false | Set to true to return results inside the response. Otherwise, the endpoint will return a URL to the output file generated. |
async | boolean | No | false | Set async to true for long processes to run in the background, API will then return a jobId which you can use with the Background Job Check endpoint. Also see Webhooks & Callbacks |
type | string | Yes | QRCode | Set the barcode type to be used. See available barcode types in the Supported Barcode Types |
value | string | Yes | - | Set the string value to encode inside the barcode, must be in a string format. |
decorationImage | string | No | - | Set this to the image that you want to be inserted the logo inside the QR-Code barcode. To use your file please upload it first to the temporary storage, see the Upload Files section. |
profiles | object | No | - | See Profiles for more information. |
outputDataFormat | string | No | - | If you require your output as base64 format, set this to base64 |
Angle | integer | No | 0 | See profiles.Angle |
NarrowBarWidth | integer | No | 3 | See profiles.NarrowBarWidth |
CaptionFont | string | No | Arial, 12 | See profiles.CaptionFont |
DataEncryptionAlgorithm | string | No | - | Controls the encryption algorithm used for data encryption. See User-Controlled Encryption for more information. The available algorithms are: AES128, AES192, AES256. |
DataEncryptionKey | string | No | - | Controls the encryption key used for data encryption. See User-Controlled Encryption for more information. |
DataEncryptionIV | string | No | - | Controls the encryption IV used for data encryption. See User-Controlled Encryption for more information. |
DataDecryptionAlgorithm | string | No | - | Controls the decryption algorithm used for data decryption. See User-Controlled Encryption for more information. The available algorithms are: AES128, AES192, AES256. |
DataDecryptionKey | string | No | - | Controls the decryption key used for data decryption. See User-Controlled Encryption for more information. |
DataDecryptionIV | string | No | - | Controls the decryption IV used for data decryption. See User-Controlled Encryption for more information. |
profiles.Angle
Specifies the barcode’s rotation angle as an integer in degrees.
| Value | Description |
| 0 | 0 degrees clockwise |
| 1 | 90 degrees clockwise |
| 2 | 180 degrees clockwise |
| 3 | 270 degrees clockwise |
{
"profiles": "{'Angle': 3}"
}
profiles.NarrowBarWidth
Specifies the width of the narrow bars in the barcode in pixels.
{
"profiles": "{'NarrowBarWidth': 3}"
}
profiles.CaptionFont
Specifies the font and size of the caption text displayed with the barcode.
{
"profiles": "{'CaptionFont': 'Arial, 12'}"
}
Query parameters
No query parameters accepted.
Responses
| Parameter | Type | Description |
url | string | Direct URL to the final PDF file stored in S3. |
outputLinkValidTill | string | Timestamp indicating when the output link will expire |
error | boolean | Indicates whether an error occurred (false means success) |
status | string | Status code of the request (200, 404, 500, etc.). For more information, see Response Codes. |
name | string | Name of the output file |
credits | integer | Number of credits consumed by the request |
remainingCredits | integer | Number of credits remaining in the account |
duration | integer | Time taken for the operation in milliseconds |
QRCode Example
Example Payload
{
"name": "barcode.png",
"value": "abcdef123456",
"type": "QRCode",
"inline": false,
"async": false,
"decorationImage": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/barcode-generator/logo.png"
}
Example Response
To see the main response codes, please refer to the
Response Codes page.
{
"url": "https://pdf-temp-files.s3.amazonaws.com/72bc579b37844d9f9e63ce06de5196d8/barcode.png",
"error": false,
"status": 200,
"name": "barcode.png",
"duration": 380,
"remainingCredits": 98725598,
"credits": 7
}
Example CURL
curl --location --request POST 'https://api.pdf.co/v1/barcode/generate' \
--header 'Content-Type: application/json' \
--header 'x-api-key: *******************' \
--data-raw '{
"name": "barcode.png",
"value": "abcdef123456",
"type": "QRCode",
"inline": false,
"async": false
}'
QRCode with Logo Inside Example
Example Payload
{
"name": "barcode.png",
"value": "abcdef123456",
"type": "QRCode",
"inline": true,
"async": false
}
Example Response
To see the main response codes, please refer to the
Response Codes page.
{
"url": "https://pdf-temp-files.s3.amazonaws.com/9a87556a8b9e4f4eae60843e697250d4/barcode.png",
"error": false,
"status": 200,
"name": "barcode.png",
"remainingCredits": 60631
}
Example CURL
curl --location --request POST 'https://api.pdf.co/v1/barcode/generate' \
--header 'Content-Type: application/json' \
--header 'x-api-key: *******************' \
--data-raw '{
"name": "barcode.png",
"value": "abcdef123456",
"type": "QRCode",
"inline": false,
"async": false,
"decorationImage": "https://pdfco-test-files.s3.us-west-2.amazonaws.com/barcode-generator/logo.png"
}'
Data URI as Output Example
Example Payload
{
"name": "barcode.png",
"value": "abcdef123456",
"type": "QRCode",
"inline": false,
"async": false
}
Example Response
To see the main response codes, please refer to the
Response Codes page.
{
"url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAYAAAA4TnrqAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAOlSURBVHhe7ZBBimMxEMVy/0v34CELkSmBjH96NhaIwKtXlY9fP5fMfawN7mNtcB9rg/tYG9zH2kAf6/V6Pa5hHeaUTPNTjftYg8Z9rEEjPdYJdoc5JZaT0imUOzopywW7w5wSy0npFModnZTlgt1hTonlpHQK5Y5ObJm5SUpODeuU3CSWE53YMnOTlJwa1im5SSwnOrFl5iYpOTWsU3KTWE50YsvMTWI5sY7lxDrMTWI50YktMzeJ5cQ6lhPrMDeJ5UQntszcJJYT61hOrMPcJJYTndgyc5Ps5ob1S24Sy4lObJm5SXZzw/olN4nlRCe2zNwku7lh/ZKbxHKik7JcsDuWE3YosXyXckcnZblgdywn7FBi+S7ljk7KcsHuWE7YocTyXcodnXD5Kck38qc0dDIdOZV8I39KQyfTkVPJN/KnNHzyZaaPrP4v7mNtcB9rA/3n6SOXxHLCDiXTfFmY9j4l03xZ0NZ0cEksJ+xQMs2XhWnvUzLNlwVtTQeXxHLCDiXTfFmY9j4l03xZSK3p+JJYTtgxC9Pe0rAOc2qkr5sOLonlhB2zMO0tDeswp0b6uungklhO2DEL097SsA5zaqSvs0PMi8Zuxzyh3En/YIeYF43djnlCuZP+wQ4xLxq7HfOEcmf7H+yo5WS3Q42puySWk9R5/2bsqOVkt0ONqbsklpPUef9m7KjlZLdDjam7JJaT1Hn/fg1+hElKTo3SIaXfLh3AjzBJyalROqT026UD+BEmKTk1SoeUfrv0BdLHHXSYUyN13r+/Tvq4gw5zaqTO+/fXSR930GFOjdR5//4Dl5+SWF7gLiWWk9Ih2uKhpySWF7hLieWkdIi2eOgpieUF7lJiOSkdoq3dQ8bJHe5SY+oujam7NHRSlgsnd7hLjam7NKbu0tBJWS6c3OEuNabu0pi6S0MntszcJJYb7NPCbp+UXZ3YMnOTWG6wTwu7fVJ2dWLLzE1iucE+Lez2SdnViS0zN0nJTWPqVsk0Xxo6sWXmJim5aUzdKpnmS0MntszcJCU3jalbJdN8aejElpmbxPJdyh12KNnNiU5smblJLN+l3GGHkt2c6MSWmZvE8l3KHXYo2c2JTspywe4wp8TywsmuoZee+jO7w5wSywsnu4ZeeurP7A5zSiwvnOwaeol/9pTEcsIONabup8RyQ1s89JTEcsIONabup8RyQ1s89JTEcsIONabup8Ryo7Uuf7mPtcF9rA3uY21wH2uD+1iZn58/9whzEbhRquEAAAAASUVORK5CYII=",
"error": false,
"status": 200,
"name": "barcode.png",
"duration": 298,
"remainingCredits": 98725605,
"credits": 7
}
Example CURL
curl --location --request POST 'https://api.pdf.co/v1/barcode/generate' \
--header 'Content-Type: application/json' \
--header 'x-api-key: *******************' \
--data-raw '{
"name": "barcode.png",
"value": "abcdef123456",
"type": "QRCode",
"inline": true,
"async": false
}'
Inconsistent URL Encoding in cURL Output: When using cURL to make API requests, the output JSON may show URL characters encoded as Unicode escape sequences. For example, the ampersand character (&) may appear as \u0026 in the cURL output. This is normal JSON encoding behavior and does not affect the validity of the URL. The URL will function correctly when used, as JSON parsers automatically decode these escape sequences. If you’re parsing the response programmatically, your JSON parser will handle this conversion automatically.
Code Samples
JavaScript/Node.js
Python
C#
Java
PHP
var https = require("https");
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
const API_KEY = "***********************************";
// Result image file name
const DestinationFile = "./barcode.png";
// Barcode type. See valid barcode types in the documentation https://developer.pdf.co
const BarcodeType = "Code128";
// Barcode value
const BarcodeValue = "qweasd123456";
// Prepare request to `Barcode Generator` API endpoint
var queryPath = `/v1/barcode/generate`;
// JSON payload for api request
var jsonPayload = JSON.stringify({
name: 'barcode.png',
type: BarcodeType,
value: BarcodeValue
});
var reqOptions = {
host: "api.pdf.co",
path: queryPath,
method: "POST",
headers: {
"x-api-key": API_KEY,
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(jsonPayload, 'utf8')
}
};
exports.handler = async (event) => {
let dataString = '';
const promise_response = await new Promise((resolve, reject) => {
// Send request
var postRequest = https.request(reqOptions, (response) => {
response.on('data', chunk => {
dataString += chunk;
});
response.on('end', () => {
resolve({
statusCode: 200,
body: JSON.stringify(JSON.parse(dataString), null, 4)
});
});
}).on("error", (e) => {
reject({
statusCode: 500,
body: 'Something went wrong!'
});
});
// Write request data
postRequest.write(jsonPayload);
postRequest.end();
});
return promise_response;
};
import os
import requests # pip install requests
# The authentication key (API Key).
# Get your own by registering at https://app.pdf.co
API_KEY = "******************************************"
# Base URL for PDF.co Web API requests
BASE_URL = "https://api.pdf.co/v1"
# Result file name
ResultFile = ".\\barcode.png"
# Barcode type. See valid barcode types in the documentation https://developer.pdf.co
BarcodeType = "Code128"
# Barcode value
BarcodeValue = "qweasd123456"
def main(args = None):
generateBarcode(ResultFile)
def generateBarcode(destinationFile):
"""Generates Barcode using PDF.co Web API"""
# Prepare requests params as JSON
# See documentation: https://developer.pdf.co/api/barcode-generator
parameters = {}
parameters["name"] = os.path.basename(destinationFile)
parameters["type"] = BarcodeType
parameters["value"] = BarcodeValue
# Prepare URL for 'Barcode Generate' API request
url = "{}/barcode/generate".format(BASE_URL)
# Execute request and get response as JSON
response = requests.post(url, data=parameters, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# Get URL of result file
resultFileUrl = json["url"]
# Download result file
r = requests.get(resultFileUrl, stream=True)
if (r.status_code == 200):
with open(destinationFile, 'wb') as file:
for chunk in r:
file.write(chunk)
print(f"Result file saved as \"{destinationFile}\" file.")
else:
print(f"Request error: {response.status_code} {response.reason}")
else:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
if __name__ == '__main__':
main()
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PDFCOWebApiExample
{
class Program
{
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
const String API_KEY = "***********************************";
// Result file name
const string ResultFileName = @".\barcode.png";
// Barcode type. See valid barcode types in the documentation https://developer.pdf.co
const string BarcodeType = "Code128";
// Barcode value
const string BarcodeValue = "qweasd123456";
static void Main(string[] args)
{
// Create standard .NET web client instance
WebClient webClient = new WebClient();
// Set API Key
webClient.Headers.Add("x-api-key", API_KEY);
// Prepare requests params as JSON
// See documentation: https://apidocs.pdf.co/#barcode-generator
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("name", Path.GetFileName(ResultFileName));
parameters.Add("type", BarcodeType);
parameters.Add("value", BarcodeValue);
// Convert dictionary of params to JSON
string jsonPayload = JsonConvert.SerializeObject(parameters);
try
{
// URL of "Barcode Generator" endpoint
string url = "https://api.pdf.co/v1/barcode/generate";
// Execute POST request with JSON payload
string response = webClient.UploadString(url, jsonPayload);
// Parse JSON response
JObject json = JObject.Parse(response);
if (json["error"].ToObject<bool>() == false)
{
// Get URL of generated barcode image file
string resultFileURI = json["url"].ToString();
// Download generated image file
webClient.DownloadFile(resultFileURI, ResultFileName);
Console.WriteLine("Generated barcode saved to \"{0}\" file.", ResultFileName);
}
else
{
Console.WriteLine(json["message"].ToString());
}
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
finally
{
webClient.Dispose();
}
Console.WriteLine();
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
}
package com.company;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;
import java.io.*;
import java.net.*;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main
{
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
final static String API_KEY = "***********************************";
// Result file name
final static Path ResultFile = Paths.get(".\\barcode.png");
// Barcode type. See valid barcode types in the documentation https://developer.pdf.co
final static String BarcodeType = "Code128";
// Barcode value
final static String BarcodeValue = "qweasd123456";
public static void main(String[] args) throws IOException
{
// Create HTTP client instance
OkHttpClient webClient = new OkHttpClient();
// Prepare URL for `Barcode Generator` API call
String query = "https://api.pdf.co/v1/barcode/generate";
// Make correctly escaped (encoded) URL
URL url = null;
try
{
url = new URI(null, query, null).toURL();
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
// Create JSON payload
String jsonPayload = String.format("{\"name\": \"%s\", \"type\": \"%s\", \"value\": \"%s\"}",
ResultFile.getFileName(),
BarcodeType,
BarcodeValue);
// Prepare request body
RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonPayload);
// Prepare request
Request request = new Request.Builder()
.url(url)
.addHeader("x-api-key", API_KEY) // (!) Set API Key
.addHeader("Content-Type", "application/json")
.post(body)
.build();
// Execute request
Response response = webClient.newCall(request).execute();
if (response.code() == 200)
{
// Parse JSON response
JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();
boolean error = json.get("error").getAsBoolean();
if (!error)
{
// Get URL of generated barcode image file
String resultFileUrl = json.get("url").getAsString();
// Download the image file
downloadFile(webClient, resultFileUrl, ResultFile);
System.out.printf("Generated barcode saved to \"%s\" file.", ResultFile.toString());
}
else
{
// Display service reported error
System.out.println(json.get("message").getAsString());
}
}
else
{
// Display request error
System.out.println(response.code() + " " + response.message());
}
}
public static void downloadFile(OkHttpClient webClient, String url, Path destinationFile) throws IOException
{
// Prepare request
Request request = new Request.Builder()
.url(url)
.build();
// Execute request
Response response = webClient.newCall(request).execute();
byte[] fileBytes = response.body().bytes();
// Save downloaded bytes to file
OutputStream output = new FileOutputStream(destinationFile.toFile());
output.write(fileBytes);
output.flush();
output.close();
response.close();
}
}
<?php
// Get submitted form data
$apiKey = $_POST["apiKey"]; // The authentication key (API Key). Get your own by registering at https://app.pdf.co
$barcodeType = $_POST["barcodeType"];
$barcodeValue = $_POST["inputValue"];
// Create URL
$url = "https://api.pdf.co/v1/barcode/generate";
// Prepare requests params
$parameters = array();
$parameters["value"] = $barcodeValue;
$parameters["type"] = $barcodeType;
// Create Json payload
$data = json_encode($parameters);
// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-type: application/json"));
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
// Execute request
$result = curl_exec($curl);
if (curl_errno($curl) == 0)
{
$status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status_code == 200)
{
$json = json_decode($result, true);
if (!isset($json["error"]) || $json["error"] == false)
{
$resultFileUrl = $json["url"];
// Display generated image
echo "<div>## Result:<img src=" . $resultFileUrl . "></div>";
}
else
{
// Display service reported errors
echo "<p>Error: " . $json["message"] . "</p>";
}
}
else
{
// Display request error
echo "<p>Status code: " . $status_code . "</p>";
echo "<p>" . $result . "</p>";
}
}
else
{
// Display CURL error
echo "Error: " . curl_error($curl);
}
// Cleanup
curl_close($curl);
?>