SQL Server Requires Chilkat v11.7.0+
SQL Server
Audit a PDF First, Optimize Only If It Is Worth It
See more PDF Optimization Examples
Demonstrates deciding whether to rewrite a PDF at all. "audit" costs a fraction of a second and changes nothing, so a batch job can audit every file and optimize only those where enough would be saved. Here the threshold is a tenth of the file; a file already as small as it can be is left alone.Chilkat SQL Server Downloads
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
DECLARE @hr int
DECLARE @iTmp0 int
DECLARE @sTmp0 nvarchar(4000)
DECLARE @success int
SELECT @success = 0
-- This example requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
-- The PDF used in this example is available at watersense_accomplishments.pdf
DECLARE @pdf int
EXEC @hr = sp_OACreate 'Chilkat.Pdf', @pdf OUT
IF @hr <> 0
BEGIN
PRINT 'Failed to create ActiveX component'
RETURN
END
EXEC sp_OAMethod @pdf, 'LoadFile', @success OUT, 'qa_data/pdf/watersense_accomplishments.pdf'
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @pdf, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @pdf
RETURN
END
DECLARE @json int
EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @json OUT
DECLARE @jsonOut int
EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @jsonOut OUT
EXEC sp_OAMethod @pdf, 'Optimize', @success OUT, 'audit', @json, @jsonOut
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @pdf, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @pdf
EXEC @hr = sp_OADestroy @json
EXEC @hr = sp_OADestroy @jsonOut
RETURN
END
DECLARE @fileSize int
EXEC sp_OAMethod @jsonOut, 'IntOf', @fileSize OUT, 'fileSize'
DECLARE @estimated int
EXEC sp_OAMethod @jsonOut, 'IntOf', @estimated OUT, 'estimatedSavings.total'
PRINT 'fileSize: ' + @fileSize
PRINT 'estimated: ' + @estimated
-- Only bother when at least a tenth of the file would go.
IF @estimated > (@fileSize / 10)
BEGIN
PRINT 'Worth optimizing.'
EXEC sp_OAMethod @pdf, 'Optimize', @success OUT, 'optimize', @json, @jsonOut
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @pdf, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @pdf
EXEC @hr = sp_OADestroy @json
EXEC @hr = sp_OADestroy @jsonOut
RETURN
END
EXEC sp_OAMethod @pdf, 'WriteFile', @success OUT, 'qa_output/watersense_optimized.pdf'
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @pdf, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @pdf
EXEC @hr = sp_OADestroy @json
EXEC @hr = sp_OADestroy @jsonOut
RETURN
END
EXEC sp_OAMethod @jsonOut, 'IntOf', @iTmp0 OUT, 'bytesSaved'
PRINT 'bytesSaved: ' + @iTmp0
END
ELSE
BEGIN
PRINT 'Already small enough; left as it is.'
END
EXEC @hr = sp_OADestroy @pdf
EXEC @hr = sp_OADestroy @json
EXEC @hr = sp_OADestroy @jsonOut
END
GO