Barcode Generator#
Available Methods#
/barcode/generate#
Generate high quality barcode images. Supports QR Code, Datamatrix, Code 39, Code 128, PDF417 and many other barcode types.
Method: POST
Endpoint: /v1/barcode/generate
Attributes#
Attribute |
Description |
Required |
---|---|---|
|
Set the string value to encode inside the barcode, must be in a |
yes |
|
Set the barcode type, must be in a |
no |
|
File name for the generated output, must be in a |
no |
|
Set the expiration time for the output link in minutes (default is |
no |
|
Must be one of: |
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 and Manage Files section below to learn how to do it. |
no, QR-Code only |
|
Set |
no |
|
Use this parameter to set additional configurations for fine-tuning and extra options. Explore the Profiles section for more. |
no |
Query parameters#
No query parameters accepted.
QRCode Example#
Payload 3#
{
"name": "barcode.png",
"value": "abcdef123456",
"type": "QRCode",
"inline": false,
"async": false
}
Response 2#
{
"url": "https://pdf-temp-files.s3.amazonaws.com/72bc579b37844d9f9e63ce06de5196d8/barcode.png",
"error": false,
"status": 200,
"name": "barcode.png",
"duration": 380,
"remainingCredits": 98725598,
"credits": 7
}
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#
Payload 3#
{
"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"
}
Response 2#
{
"url": "https://pdf-temp-files.s3.amazonaws.com/9a87556a8b9e4f4eae60843e697250d4/barcode.png",
"error": false,
"status": 200,
"name": "barcode.png",
"remainingCredits": 60631
}
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#
Payload 3#
{
"name": "barcode.png",
"value": "abcdef123456",
"type": "QRCode",
"inline": true,
"async": false
}
Response 2#
{
"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
}
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
}'
Code samples#
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/index.html
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);
?>
On Github#
Footnotes
- 1
Supports publicly accessible links from any source, including Google Drive, Dropbox, and PDF.co Built-In Files Storage. To upload files via the API, check out the File Upload section. Note: If you experience intermittent Access Denied or Too Many Requests errors, please try adding
cache:
to enable built-in URL caching (e.g.,cache:https://example.com/file1.pdf
). For data security, you have the option to encrypt output files and decrypt input files. Learn more about user-controlled data encryption.- 2(1,2,3)
Main response codes as follows:
Code
Description
200
Success
400
Bad request. Typically happens because of bad input parameters, or because the input URLs can’t be reached, possibly due to access restrictions like needing a login or password.
401
Unauthorized
402
Not enough credits
445
Timeout error. To process large documents or files please use asynchronous mode (set the
async
parameter totrue
) and then check status using the /job/check endpoint. If a file contains many pages then specify a page range using thepages
parameter. The number of pages of the document can be obtained using the /pdf/info endpoint.Note
For more see the complete list of available response codes.
- 3(1,2,3)
PDF.co Request size: API requests do not support request sizes of more than
4
megabytes in size. Please ensure that request sizes do not exceed this limit.