SQL Server Requires Chilkat v11.7.0+
SQL Server
Extract PDF Text to a StringBuilder and Save to a File
See more PDF Text Extraction Examples
Demonstrates ExtractTextSb, which writes the extracted text to a StringBuilder instead of returning it as a JSON string. Use it for large documents. The JSON output still receives the quality report.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 long_report.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/long_report.pdf'
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @pdf, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @pdf
RETURN
END
EXEC sp_OAGetProperty @pdf, 'NumPages', @iTmp0 OUT
PRINT 'Number of pages: ' + @iTmp0
-- ExtractTextSb takes the same operation and options as ExtractText, but the text
-- goes to a StringBuilder. This avoids building a very large JSON string for
-- documents with many pages.
DECLARE @json int
EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @json OUT
DECLARE @sbText int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbText OUT
DECLARE @jsonOut int
EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @jsonOut OUT
EXEC sp_OAMethod @pdf, 'ExtractTextSb', @success OUT, 'text', @json, @sbText, @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 @sbText
EXEC @hr = sp_OADestroy @jsonOut
RETURN
END
EXEC sp_OAGetProperty @sbText, 'Length', @iTmp0 OUT
PRINT 'Extracted ' + @iTmp0 + ' characters.'
-- Save the text to a file.
EXEC sp_OAMethod @sbText, 'WriteFile', @success OUT, 'qa_output/long_report.txt', 'utf-8', 0
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @sbText, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @pdf
EXEC @hr = sp_OADestroy @json
EXEC @hr = sp_OADestroy @sbText
EXEC @hr = sp_OADestroy @jsonOut
RETURN
END
-- The JSON output does not contain the text, but it still has the quality report.
EXEC sp_OAMethod @jsonOut, 'StringOf', @sTmp0 OUT, 'quality.rating'
PRINT 'Quality: ' + @sTmp0
EXEC sp_OAMethod @jsonOut, 'StringOf', @sTmp0 OUT, 'quality.pagesNeedingOcr'
PRINT 'Pages with no text (need OCR): [' + @sTmp0 + ']'
-- Sample output:
-- Number of pages: 3
-- Extracted 4522 characters.
-- Quality: good
-- Pages with no text (need OCR): []
EXEC @hr = sp_OADestroy @pdf
EXEC @hr = sp_OADestroy @json
EXEC @hr = sp_OADestroy @sbText
EXEC @hr = sp_OADestroy @jsonOut
END
GO