Sample code for 30+ languages & platforms
Lua Requires Chilkat v9.5.0.95+

Extract Embedded Files from PDF

Demonstrates how to get information about the embedded files (if any) contained within a PDF, and shows how to extract each file.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- This example requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.

local pdf = chilkat.Pdf.new()

local success = pdf:load_file("qa_data/pdf/embedded_files/my_embedded_files_test.pdf")
if not success then
    print(pdf.last_error_text)
    return
end

-- How many embedded files exist within the opened PDF?
local numFiles = pdf.num_embedded_files
print("Number of embedded files: " .. numFiles)

local json = chilkat.JsonObject.new()
json.emit_compact = false

local bd = chilkat.BinData.new()

-- Get information about each file, and extract each to the filesystem.
local i = 0
while i < numFiles do
    success = pdf:get_embedded_file_info(i, json)
    if not success then
        print(pdf.last_error_text)
        return
    end

    print(json:emit())

    -- Get the filename from the JSON.
    local filename = "someFile.dat"

    -- The filename SHOULD always be present..
    if json:has_member("filename") then
        filename = json:string_of("filename")
    end

    -- Get the file data.
    success = pdf:get_embedded_file_bd(i, bd)
    if not success then
        print(pdf.last_error_text)
        return
    end

    -- Save the contents of the bd to the filename (in the current working directory) in the filesystem.
    success = bd:write_file(filename)
    if not success then
        print("Failed to write output file.")
    end

    i = i + 1
end

-- Sample output for the above code:

-- Number of embedded files: 3
-- {
--   "filename": "employees.json",
--   "desc": "JSON",
--   "subType": "application/json",
--   "size": 159,
--   "creationDate": "D:20230715170506-05'00'",
--   "modDate": "D:20160207153838-05'00'"
-- }
--
-- {
--   "filename": "rsaPubKey.pem",
--   "desc": "RSA Public Key PEM",
--   "size": 451,
--   "creationDate": "D:20230715170546-05'00'",
--   "modDate": "D:20150724133153-05'00'"
-- }
--
-- {
--   "filename": "starfish.jpg",
--   "desc": "Starfish JPG",
--   "subType": "image/jpeg",
--   "size": 6229,
--   "creationDate": "D:20230715170356-05'00'",
--   "modDate": "D:20080529103055-05'00'"
-- }