Automate File Conversions in PowerShell

Tomas, CEO

In this blog post, I will show how to easily convert files (e.g., DOCX to PDF) programmatically using ConvertAPI and PowerShell on Windows. PowerShell can be useful for creating automation file conversion scripts for Windows and Servers.

Why Use ConvertAPI?

ConvertAPI is a versatile file conversion service that supports various formats. It's particularly useful when automating tasks like batch file conversion or integrating file processing into your workflows.

Prerequisites

  1. ConvertAPI Account: Sign up at ConvertAPI and obtain your API secret from the API secret page.
  2. PowerShell: Installed on your system (default on most Windows systems). When running the script, you might encounter the following error \run.ps1 cannot be loaded because running scripts is disabled on this system. This happens because PowerShell's execution policy restricts the running of scripts for security reasons. You can temporarily bypass this restriction by allowing scripts to run in the current session. Run the following command before executing the script: Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

PowerShell Script for File Conversion

Here's a PowerShell script to convert a DOCX file to a PDF using ConvertAPI:

# Define the API key and endpoint
$ApiSecret = "Secret can be obtained from https://www.convertapi.com/a/secret"
$ApiUrl = "https://v2.convertapi.com/convert/docx/to/pdf?StoreFile=true"

# Define the input file path (adjust as needed)
$InputFilePath = "C:\document1.docx"

# Define the output directory
$OutputDirectory = "C:\output"

# Check if the input file exists
if (!(Test-Path $InputFilePath)) {
    Write-Host "Input file does not exist: $InputFilePath" -ForegroundColor Red
    exit
}

# Ensure the output directory exists
if (!(Test-Path $OutputDirectory)) {
    New-Item -ItemType Directory -Path $OutputDirectory | Out-Null
}

# Extract the file name from the input file path
$FileName = [System.IO.Path]::GetFileName($InputFilePath)

# Read the file content as bytes
$FileBytes = [System.IO.File]::ReadAllBytes($InputFilePath)

# Prepare headers for the request
$Headers = @{
    "Content-Type"        = "application/octet-stream"
    "Accept"              = "application/json"
    "Authorization"       = "Bearer $ApiSecret"
    "Content-Disposition" = "attachment; filename=`"$FileName`""
}

# Send the file to ConvertAPI
try {
    $Response = Invoke-RestMethod -Uri $ApiUrl `
        -Method POST `
        -Headers $Headers `
        -Body $FileBytes `
        -ContentType "application/octet-stream" `
        -ErrorAction Stop

    # Iterate over all files in the response
    foreach ($File in $Response.Files) {
        $FileUrl = $File.Url
        $OutputFileName = $File.FileName
        $OutputFilePath = Join-Path $OutputDirectory $OutputFileName

        # Download the file
        Invoke-WebRequest -Uri $FileUrl -OutFile $OutputFilePath

        Write-Host "File downloaded successfully: $OutputFilePath" -ForegroundColor Green
    }
} catch {
    # Gracefully handle cases where Response is null
    if ($_.Exception.Response -ne $null) {
        $ErrorDetails = $_.Exception.Response.GetResponseStream()
        $StreamReader = New-Object System.IO.StreamReader($ErrorDetails)
        $ErrorBody = $StreamReader.ReadToEnd()
        $StreamReader.Close()

        Write-Host "An error occurred:" -ForegroundColor Red
        Write-Host $ErrorBody -ForegroundColor Yellow
    } else {
        Write-Host "An error occurred, but no response was received:" -ForegroundColor Red
        Write-Host $_.Exception.Message -ForegroundColor Yellow
    }
}

How It Works

  1. API Key: Replace $ApiSecret with your ConvertAPI secret obtained from your account dashboard.
  2. File Input: Specify the file to convert (C:\document1.docx in this example).
  3. Output Directory: Define where the converted files will be saved.
  4. Conversion Request: The script sends the file to the ConvertAPI endpoint for conversion.
  5. File Download: The converted file(s) are downloaded to the specified output directory.

Handling Errors

The script includes error handling to capture API errors or connectivity issues, ensuring you receive detailed feedback if something goes wrong.

Conclusion

With just a few lines of PowerShell, you can harness the power of ConvertAPI for robust file conversion. This setup is perfect for automating repetitive file processing tasks, saving you time and effort. Give it a try, and take your workflows to the next level!