Generate Excel and PDF in Oracle and Send Report by Email

First Install UTL_MAIL ###

To install UTL_MAIL:

sqlplus sys/****
 @$ORACLE_HOME/rdbms/admin/utlmail.sql
 @$ORACLE_HOME/rdbms/admin/prvtmail.plb

### Create a Reporting User ###

create user tctreport identified by tctreport;

grant connect to tctreport;

grant dba to tctreport;

sqlplus tctreport/tctreport

## Grant TCTREPORT User permission to execute UTL_MAIL ##

sqlplus "/as sysdba"

grant execute on sys.utl_mail to tctreport;

 

## Create Directory MY_DIR as location to generate the files ###

create or replace directory MY_DIR as '/ACFS/report';

grant read, write on directory MY_DIR to tctreport;

 

##################################################################################################################

1. Generate Excel by first creating a procedure as_xlsx (code is in file a3_excel.sql )

Can be downloaded from:

https://technology.amis.nl/wp-content/uploads/2011/02/as_xlsx11.txt

sqlplus tctreport/tctreport

CREATE OR REPLACE package as_xlsx
 is
 /**********************************************
 **
 ** Author: Anton Scheffer
 ** Date: 19-02-2011
 ** Website: http://technology.amis.nl/blog
 ** See also: http://technology.amis.nl/blog/?p=10995
 **
 ** Changelog:
 ** Date: 21-02-2011
 ** Added Aligment, horizontal, vertical, wrapText
 ** Date: 06-03-2011
 ** Added Comments, MergeCells, fixed bug for dependency on NLS-settings
 ** Date: 16-03-2011
 ** Added bold and italic fonts
 ** Date: 22-03-2011
 ** Fixed issue with timezone's set to a region(name) instead of a offset
 ** Date: 08-04-2011
 ** Fixed issue with XML-escaping from text
 ** Date: 27-05-2011
 ** Added MIT-license
 ** Date: 11-08-2011
 ** Fixed NLS-issue with column width
 ** Date: 29-09-2011
 ** Added font color
 ** Date: 16-10-2011
 ** fixed bug in add_string
 ** Date: 26-04-2012
 ** Fixed set_autofilter (only one autofilter per sheet, added _xlnm._FilterDatabase)
 ** Added list_validation = drop-down
 ** Date: 27-08-2013
 ** Added freeze_pane
 **
 ******************************************************************************
 ******************************************************************************
 Copyright (C) 2011, 2012 by Anton Scheffer

Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.

******************************************************************************
 ******************************************** */
 --
 type tp_alignment is record
 ( vertical varchar2(11)
 , horizontal varchar2(16)
 , wrapText boolean
 );
 --
 procedure clear_workbook;
 --
 procedure new_sheet( p_sheetname varchar2 := null );
 --
 function OraFmt2Excel( p_format varchar2 := null )
 return varchar2;
 --
 function get_numFmt( p_format varchar2 := null )
 return pls_integer;
 --
 function get_font
 ( p_name varchar2
 , p_family pls_integer := 2
 , p_fontsize number := 11
 , p_theme pls_integer := 1
 , p_underline boolean := false
 , p_italic boolean := false
 , p_bold boolean := false
 , p_rgb varchar2 := null -- this is a hex ALPHA Red Green Blue value
 )
 return pls_integer;
 --
 function get_fill
 ( p_patternType varchar2
 , p_fgRGB varchar2 := null -- this is a hex ALPHA Red Green Blue value
 )
 return pls_integer;
 --
 function get_border
 ( p_top varchar2 := 'thin'
 , p_bottom varchar2 := 'thin'
 , p_left varchar2 := 'thin'
 , p_right varchar2 := 'thin'
 )
 /*
 none
 thin
 medium
 dashed
 dotted
 thick
 double
 hair
 mediumDashed
 dashDot
 mediumDashDot
 dashDotDot
 mediumDashDotDot
 slantDashDot
 */
 return pls_integer;
 --
 function get_alignment
 ( p_vertical varchar2 := null
 , p_horizontal varchar2 := null
 , p_wrapText boolean := null
 )
 /* horizontal
 center
 centerContinuous
 distributed
 fill
 general
 justify
 left
 right
 */
 /* vertical
 bottom
 center
 distributed
 justify
 top
 */
 return tp_alignment;
 --
 procedure cell
 ( p_col pls_integer
 , p_row pls_integer
 , p_value number
 , p_numFmtId pls_integer := null
 , p_fontId pls_integer := null
 , p_fillId pls_integer := null
 , p_borderId pls_integer := null
 , p_alignment tp_alignment := null
 , p_sheet pls_integer := null
 );
 --
 procedure cell
 ( p_col pls_integer
 , p_row pls_integer
 , p_value varchar2
 , p_numFmtId pls_integer := null
 , p_fontId pls_integer := null
 , p_fillId pls_integer := null
 , p_borderId pls_integer := null
 , p_alignment tp_alignment := null
 , p_sheet pls_integer := null
 );
 --
 procedure cell
 ( p_col pls_integer
 , p_row pls_integer
 , p_value date
 , p_numFmtId pls_integer := null
 , p_fontId pls_integer := null
 , p_fillId pls_integer := null
 , p_borderId pls_integer := null
 , p_alignment tp_alignment := null
 , p_sheet pls_integer := null
 );
 --
 procedure hyperlink
 ( p_col pls_integer
 , p_row pls_integer
 , p_url varchar2
 , p_value varchar2 := null
 , p_sheet pls_integer := null
 );
 --
 procedure comment
 ( p_col pls_integer
 , p_row pls_integer
 , p_text varchar2
 , p_author varchar2 := null
 , p_width pls_integer := 150 -- pixels
 , p_height pls_integer := 100 -- pixels
 , p_sheet pls_integer := null
 );
 --
 procedure mergecells
 ( p_tl_col pls_integer -- top left
 , p_tl_row pls_integer
 , p_br_col pls_integer -- bottom right
 , p_br_row pls_integer
 , p_sheet pls_integer := null
 );
 --
 procedure list_validation
 ( p_sqref_col pls_integer
 , p_sqref_row pls_integer
 , p_tl_col pls_integer -- top left
 , p_tl_row pls_integer
 , p_br_col pls_integer -- bottom right
 , p_br_row pls_integer
 , p_style varchar2 := 'stop' -- stop, warning, information
 , p_title varchar2 := null
 , p_prompt varchar := null
 , p_show_error boolean := false
 , p_error_title varchar2 := null
 , p_error_txt varchar2 := null
 , p_sheet pls_integer := null
 );
 --
 procedure list_validation
 ( p_sqref_col pls_integer
 , p_sqref_row pls_integer
 , p_defined_name varchar2
 , p_style varchar2 := 'stop' -- stop, warning, information
 , p_title varchar2 := null
 , p_prompt varchar := null
 , p_show_error boolean := false
 , p_error_title varchar2 := null
 , p_error_txt varchar2 := null
 , p_sheet pls_integer := null
 );
 --
 procedure defined_name
 ( p_tl_col pls_integer -- top left
 , p_tl_row pls_integer
 , p_br_col pls_integer -- bottom right
 , p_br_row pls_integer
 , p_name varchar2
 , p_sheet pls_integer := null
 , p_localsheet pls_integer := null
 );
 --
 procedure set_column_width
 ( p_col pls_integer
 , p_width number
 , p_sheet pls_integer := null
 );
 --
 procedure set_column
 ( p_col pls_integer
 , p_numFmtId pls_integer := null
 , p_fontId pls_integer := null
 , p_fillId pls_integer := null
 , p_borderId pls_integer := null
 , p_alignment tp_alignment := null
 , p_sheet pls_integer := null
 );
 --
 procedure set_row
 ( p_row pls_integer
 , p_numFmtId pls_integer := null
 , p_fontId pls_integer := null
 , p_fillId pls_integer := null
 , p_borderId pls_integer := null
 , p_alignment tp_alignment := null
 , p_sheet pls_integer := null
 );
 --
 procedure freeze_rows
 ( p_nr_rows pls_integer := 1
 , p_sheet pls_integer := null
 );
 --
 procedure freeze_cols
 ( p_nr_cols pls_integer := 1
 , p_sheet pls_integer := null
 );
 --
 procedure freeze_pane
 ( p_col pls_integer
 , p_row pls_integer
 , p_sheet pls_integer := null
 );
 --
 procedure set_autofilter
 ( p_column_start pls_integer := null
 , p_column_end pls_integer := null
 , p_row_start pls_integer := null
 , p_row_end pls_integer := null
 , p_sheet pls_integer := null
 );
 --
 function finish
 return blob;
 --
 procedure save
 ( p_directory varchar2
 , p_filename varchar2
 );
 --
 procedure query2sheet
 ( p_sql varchar2
 , p_column_headers boolean := true
 , p_directory varchar2 := null
 , p_filename varchar2 := null
 , p_sheet pls_integer := null
 );
 --
 /* Example
 begin
 as_xlsx.clear_workbook;
 as_xlsx.new_sheet;
 as_xlsx.cell( 5, 1, 5 );
 as_xlsx.cell( 3, 1, 3 );
 as_xlsx.cell( 2, 2, 45 );
 as_xlsx.cell( 3, 2, 'Anton Scheffer', p_alignment => as_xlsx.get_alignment( p_wraptext => true ) );
 as_xlsx.cell( 1, 4, sysdate, p_fontId => as_xlsx.get_font( 'Calibri', p_rgb => 'FFFF0000' ) );
 as_xlsx.cell( 2, 4, sysdate, p_numFmtId => as_xlsx.get_numFmt( 'dd/mm/yyyy h:mm' ) );
 as_xlsx.cell( 3, 4, sysdate, p_numFmtId => as_xlsx.get_numFmt( as_xlsx.orafmt2excel( 'dd/mon/yyyy' ) ) );
 as_xlsx.cell( 5, 5, 75, p_borderId => as_xlsx.get_border( 'double', 'double', 'double', 'double' ) );
 as_xlsx.cell( 2, 3, 33 );
 as_xlsx.hyperlink( 1, 6, 'http://www.amis.nl', 'Amis site' );
 as_xlsx.cell( 1, 7, 'Some merged cells', p_alignment => as_xlsx.get_alignment( p_horizontal => 'center' ) );
 as_xlsx.mergecells( 1, 7, 3, 7 );
 for i in 1 .. 5
 loop
 as_xlsx.comment( 3, i + 3, 'Row ' || (i+3), 'Anton' );
 end loop;
 as_xlsx.new_sheet;
 as_xlsx.set_row( 1, p_fillId => as_xlsx.get_fill( 'solid', 'FFFF0000' ) ) ;
 for i in 1 .. 5
 loop
 as_xlsx.cell( 1, i, i );
 as_xlsx.cell( 2, i, i * 3 );
 as_xlsx.cell( 3, i, 'x ' || i * 3 );
 end loop;
 as_xlsx.query2sheet( 'select rownum, x.*
 , case when mod( rownum, 2 ) = 0 then rownum * 3 end demo
 , case when mod( rownum, 2 ) = 1 then ''demo '' || rownum end demo2 from dual x connect by rownum <= 5' );
 as_xlsx.save( 'MY_DIR', 'my.xlsx' );
 end;
 --
 begin
 as_xlsx.clear_workbook;
 as_xlsx.new_sheet;
 as_xlsx.cell( 1, 6, 5 );
 as_xlsx.cell( 1, 7, 3 );
 as_xlsx.cell( 1, 8, 7 );
 as_xlsx.new_sheet;
 as_xlsx.cell( 2, 6, 15, p_sheet => 2 );
 as_xlsx.cell( 2, 7, 13, p_sheet => 2 );
 as_xlsx.cell( 2, 8, 17, p_sheet => 2 );
 as_xlsx.list_validation( 6, 3, 1, 6, 1, 8, p_show_error => true, p_sheet => 1 );
 as_xlsx.defined_name( 2, 6, 2, 8, 'Anton', 2 );
 as_xlsx.list_validation
 ( 6, 1, 'Anton'
 , p_style => 'information'
 , p_title => 'valid values are'
 , p_prompt => '13, 15 and 17'
 , p_show_error => true
 , p_error_title => 'Are you sure?'
 , p_error_txt => 'Valid values are: 13, 15 and 17'
 , p_sheet => 1 );
 as_xlsx.save( 'MY_DIR', 'my.xlsx' );
 end;
 --
 begin
 as_xlsx.clear_workbook;
 as_xlsx.new_sheet;
 as_xlsx.cell( 1, 6, 5 );
 as_xlsx.cell( 1, 7, 3 );
 as_xlsx.cell( 1, 8, 7 );
 as_xlsx.set_autofilter( 1,1, p_row_start => 5, p_row_end => 8 );
 as_xlsx.new_sheet;
 as_xlsx.cell( 2, 6, 5 );
 as_xlsx.cell( 2, 7, 3 );
 as_xlsx.cell( 2, 8, 7 );
 as_xlsx.set_autofilter( 2,2, p_row_start => 5, p_row_end => 8 );
 as_xlsx.save( 'MY_DIR', 'my.xlsx' );
 end;
 --
 begin
 as_xlsx.clear_workbook;
 as_xlsx.new_sheet;
 for c in 1 .. 10
 loop
 as_xlsx.cell( c, 1, 'COL' || c );
 as_xlsx.cell( c, 2, 'val' || c );
 as_xlsx.cell( c, 3, c );
 end loop;
 as_xlsx.freeze_rows( 1 );
 as_xlsx.new_sheet;
 for r in 1 .. 10
 loop
 as_xlsx.cell( 1, r, 'ROW' || r );
 as_xlsx.cell( 2, r, 'val' || r );
 as_xlsx.cell( 3, r, r );
 end loop;
 as_xlsx.freeze_cols( 3 );
 as_xlsx.new_sheet;
 as_xlsx.cell( 3, 3, 'Start freeze' );
 as_xlsx.freeze_pane( 3,3 );
 as_xlsx.save( 'MY_DIR', 'my.xlsx' );
 end;
 */
 end;
 /

CREATE OR REPLACE package body as_xlsx
 is
 --
 c_LOCAL_FILE_HEADER constant raw(4) := hextoraw( '504B0304' ); -- Local file header signature
 c_END_OF_CENTRAL_DIRECTORY constant raw(4) := hextoraw( '504B0506' ); -- End of central directory signature
 --
 type tp_XF_fmt is record
 ( numFmtId pls_integer
 , fontId pls_integer
 , fillId pls_integer
 , borderId pls_integer
 , alignment tp_alignment
 );
 type tp_col_fmts is table of tp_XF_fmt index by pls_integer;
 type tp_row_fmts is table of tp_XF_fmt index by pls_integer;
 type tp_widths is table of number index by pls_integer;
 type tp_cell is record
 ( value number
 , style varchar2(50)
 );
 type tp_cells is table of tp_cell index by pls_integer;
 type tp_rows is table of tp_cells index by pls_integer;
 type tp_autofilter is record
 ( column_start pls_integer
 , column_end pls_integer
 , row_start pls_integer
 , row_end pls_integer
 );
 type tp_autofilters is table of tp_autofilter index by pls_integer;
 type tp_hyperlink is record
 ( cell varchar2(10)
 , url varchar2(1000)
 );
 type tp_hyperlinks is table of tp_hyperlink index by pls_integer;
 subtype tp_author is varchar2(32767 char);
 type tp_authors is table of pls_integer index by tp_author;
 authors tp_authors;
 type tp_comment is record
 ( text varchar2(32767 char)
 , author tp_author
 , row pls_integer
 , column pls_integer
 , width pls_integer
 , height pls_integer
 );
 type tp_comments is table of tp_comment index by pls_integer;
 type tp_mergecells is table of varchar2(21) index by pls_integer;
 type tp_validation is record
 ( type varchar2(10)
 , errorstyle varchar2(32)
 , showinputmessage boolean
 , prompt varchar2(32767 char)
 , title varchar2(32767 char)
 , error_title varchar2(32767 char)
 , error_txt varchar2(32767 char)
 , showerrormessage boolean
 , formula1 varchar2(32767 char)
 , formula2 varchar2(32767 char)
 , allowBlank boolean
 , sqref varchar2(32767 char)
 );
 type tp_validations is table of tp_validation index by pls_integer;
 type tp_sheet is record
 ( rows tp_rows
 , widths tp_widths
 , name varchar2(100)
 , freeze_rows pls_integer
 , freeze_cols pls_integer
 , autofilters tp_autofilters
 , hyperlinks tp_hyperlinks
 , col_fmts tp_col_fmts
 , row_fmts tp_row_fmts
 , comments tp_comments
 , mergecells tp_mergecells
 , validations tp_validations
 );
 type tp_sheets is table of tp_sheet index by pls_integer;
 type tp_numFmt is record
 ( numFmtId pls_integer
 , formatCode varchar2(100)
 );
 type tp_numFmts is table of tp_numFmt index by pls_integer;
 type tp_fill is record
 ( patternType varchar2(30)
 , fgRGB varchar2(8)
 );
 type tp_fills is table of tp_fill index by pls_integer;
 type tp_cellXfs is table of tp_xf_fmt index by pls_integer;
 type tp_font is record
 ( name varchar2(100)
 , family pls_integer
 , fontsize number
 , theme pls_integer
 , RGB varchar2(8)
 , underline boolean
 , italic boolean
 , bold boolean
 );
 type tp_fonts is table of tp_font index by pls_integer;
 type tp_border is record
 ( top varchar2(17)
 , bottom varchar2(17)
 , left varchar2(17)
 , right varchar2(17)
 );
 type tp_borders is table of tp_border index by pls_integer;
 type tp_numFmtIndexes is table of pls_integer index by pls_integer;
 type tp_strings is table of pls_integer index by varchar2(32767 char);
 type tp_str_ind is table of varchar2(32767 char) index by pls_integer;
 type tp_defined_name is record
 ( name varchar2(32767 char)
 , ref varchar2(32767 char)
 , sheet pls_integer
 );
 type tp_defined_names is table of tp_defined_name index by pls_integer;
 type tp_book is record
 ( sheets tp_sheets
 , strings tp_strings
 , str_ind tp_str_ind
 , str_cnt pls_integer := 0
 , fonts tp_fonts
 , fills tp_fills
 , borders tp_borders
 , numFmts tp_numFmts
 , cellXfs tp_cellXfs
 , numFmtIndexes tp_numFmtIndexes
 , defined_names tp_defined_names
 );
 workbook tp_book;
 --
 procedure blob2file
 ( p_blob blob
 , p_directory varchar2 := 'MY_DIR'
 , p_filename varchar2 := 'my.xlsx'
 )
 is
 t_fh utl_file.file_type;
 t_len pls_integer := 32767;
 begin
 t_fh := utl_file.fopen( p_directory
 , p_filename
 , 'wb'
 );
 for i in 0 .. trunc( ( dbms_lob.getlength( p_blob ) - 1 ) / t_len )
 loop
 utl_file.put_raw( t_fh
 , dbms_lob.substr( p_blob
 , t_len
 , i * t_len + 1
 )
 );
 end loop;
 utl_file.fclose( t_fh );
 end;
 --
 function raw2num( p_raw raw, p_len integer, p_pos integer )
 return number
 is
 begin
 return utl_raw.cast_to_binary_integer( utl_raw.substr( p_raw, p_pos, p_len ), utl_raw.little_endian );
 end;
 --
 function little_endian( p_big number, p_bytes pls_integer := 4 )
 return raw
 is
 begin
 return utl_raw.substr( utl_raw.cast_from_binary_integer( p_big, utl_raw.little_endian ), 1, p_bytes );
 end;
 --
 function blob2num( p_blob blob, p_len integer, p_pos integer )
 return number
 is
 begin
 return utl_raw.cast_to_binary_integer( dbms_lob.substr( p_blob, p_len, p_pos ), utl_raw.little_endian );
 end;
 --
 procedure add1file
 ( p_zipped_blob in out blob
 , p_name varchar2
 , p_content blob
 )
 is
 t_now date;
 t_blob blob;
 t_len integer;
 t_clen integer;
 t_crc32 raw(4) := hextoraw( '00000000' );
 t_compressed boolean := false;
 t_name raw(32767);
 begin
 t_now := sysdate;
 t_len := nvl( dbms_lob.getlength( p_content ), 0 );
 if t_len > 0
 then
 t_blob := utl_compress.lz_compress( p_content );
 t_clen := dbms_lob.getlength( t_blob ) - 18;
 t_compressed := t_clen < t_len;
 t_crc32 := dbms_lob.substr( t_blob, 4, t_clen + 11 );
 end if;
 if not t_compressed
 then
 t_clen := t_len;
 t_blob := p_content;
 end if;
 if p_zipped_blob is null
 then
 dbms_lob.createtemporary( p_zipped_blob, true );
 end if;
 t_name := utl_i18n.string_to_raw( p_name, 'AL32UTF8' );
 dbms_lob.append( p_zipped_blob
 , utl_raw.concat( c_LOCAL_FILE_HEADER -- Local file header signature
 , hextoraw( '1400' ) -- version 2.0
 , case when t_name = utl_i18n.string_to_raw( p_name, 'US8PC437' )
 then hextoraw( '0000' ) -- no General purpose bits
 else hextoraw( '0008' ) -- set Language encoding flag (EFS)
 end
 , case when t_compressed
 then hextoraw( '0800' ) -- deflate
 else hextoraw( '0000' ) -- stored
 end
 , little_endian( to_number( to_char( t_now, 'ss' ) ) / 2
 + to_number( to_char( t_now, 'mi' ) ) * 32
 + to_number( to_char( t_now, 'hh24' ) ) * 2048
 , 2
 ) -- File last modification time
 , little_endian( to_number( to_char( t_now, 'dd' ) )
 + to_number( to_char( t_now, 'mm' ) ) * 32
 + ( to_number( to_char( t_now, 'yyyy' ) ) - 1980 ) * 512
 , 2
 ) -- File last modification date
 , t_crc32 -- CRC-32
 , little_endian( t_clen ) -- compressed size
 , little_endian( t_len ) -- uncompressed size
 , little_endian( utl_raw.length( t_name ), 2 ) -- File name length
 , hextoraw( '0000' ) -- Extra field length
 , t_name -- File name
 )
 );
 if t_compressed
 then
 dbms_lob.copy( p_zipped_blob, t_blob, t_clen, dbms_lob.getlength( p_zipped_blob ) + 1, 11 ); -- compressed content
 elsif t_clen > 0
 then
 dbms_lob.copy( p_zipped_blob, t_blob, t_clen, dbms_lob.getlength( p_zipped_blob ) + 1, 1 ); -- content
 end if;
 if dbms_lob.istemporary( t_blob ) = 1
 then
 dbms_lob.freetemporary( t_blob );
 end if;
 end;
 --
 procedure finish_zip( p_zipped_blob in out blob )
 is
 t_cnt pls_integer := 0;
 t_offs integer;
 t_offs_dir_header integer;
 t_offs_end_header integer;
 t_comment raw(32767) := utl_raw.cast_to_raw( 'Implementation by Anton Scheffer' );
 begin
 t_offs_dir_header := dbms_lob.getlength( p_zipped_blob );
 t_offs := 1;
 while dbms_lob.substr( p_zipped_blob, utl_raw.length( c_LOCAL_FILE_HEADER ), t_offs ) = c_LOCAL_FILE_HEADER
 loop
 t_cnt := t_cnt + 1;
 dbms_lob.append( p_zipped_blob
 , utl_raw.concat( hextoraw( '504B0102' ) -- Central directory file header signature
 , hextoraw( '1400' ) -- version 2.0
 , dbms_lob.substr( p_zipped_blob, 26, t_offs + 4 )
 , hextoraw( '0000' ) -- File comment length
 , hextoraw( '0000' ) -- Disk number where file starts
 , hextoraw( '0000' ) -- Internal file attributes =>
 -- 0000 binary file
 -- 0100 (ascii)text file
 , case
 when dbms_lob.substr( p_zipped_blob
 , 1
 , t_offs + 30 + blob2num( p_zipped_blob, 2, t_offs + 26 ) - 1
 ) in ( hextoraw( '2F' ) -- /
 , hextoraw( '5C' ) -- \
 )
 then hextoraw( '10000000' ) -- a directory/folder
 else hextoraw( '2000B681' ) -- a file
 end -- External file attributes
 , little_endian( t_offs - 1 ) -- Relative offset of local file header
 , dbms_lob.substr( p_zipped_blob
 , blob2num( p_zipped_blob, 2, t_offs + 26 )
 , t_offs + 30
 ) -- File name
 )
 );
 t_offs := t_offs + 30 + blob2num( p_zipped_blob, 4, t_offs + 18 ) -- compressed size
 + blob2num( p_zipped_blob, 2, t_offs + 26 ) -- File name length
 + blob2num( p_zipped_blob, 2, t_offs + 28 ); -- Extra field length
 end loop;
 t_offs_end_header := dbms_lob.getlength( p_zipped_blob );
 dbms_lob.append( p_zipped_blob
 , utl_raw.concat( c_END_OF_CENTRAL_DIRECTORY -- End of central directory signature
 , hextoraw( '0000' ) -- Number of this disk
 , hextoraw( '0000' ) -- Disk where central directory starts
 , little_endian( t_cnt, 2 ) -- Number of central directory records on this disk
 , little_endian( t_cnt, 2 ) -- Total number of central directory records
 , little_endian( t_offs_end_header - t_offs_dir_header ) -- Size of central directory
 , little_endian( t_offs_dir_header ) -- Offset of start of central directory, relative to start of archive
 , little_endian( nvl( utl_raw.length( t_comment ), 0 ), 2 ) -- ZIP file comment length
 , t_comment
 )
 );
 end;
 --
 function alfan_col( p_col pls_integer )
 return varchar2
 is
 begin
 return case
 when p_col > 702 then chr( 64 + trunc( ( p_col - 27 ) / 676 ) ) || chr( 65 + mod( trunc( ( p_col - 1 ) / 26 ) - 1, 26 ) ) || chr( 65 + mod( p_col - 1, 26 ) )
 when p_col > 26 then chr( 64 + trunc( ( p_col - 1 ) / 26 ) ) || chr( 65 + mod( p_col - 1, 26 ) )
 else chr( 64 + p_col )
 end;
 end;
 --
 function col_alfan( p_col varchar2 )
 return pls_integer
 is
 begin
 return ascii( substr( p_col, -1 ) ) - 64
 + nvl( ( ascii( substr( p_col, -2, 1 ) ) - 64 ) * 26, 0 )
 + nvl( ( ascii( substr( p_col, -3, 1 ) ) - 64 ) * 676, 0 );
 end;
 --
 procedure clear_workbook
 is
 t_row_ind pls_integer;
 begin
 for s in 1 .. workbook.sheets.count()
 loop
 t_row_ind := workbook.sheets( s ).rows.first();
 while t_row_ind is not null
 loop
 workbook.sheets( s ).rows( t_row_ind ).delete();
 t_row_ind := workbook.sheets( s ).rows.next( t_row_ind );
 end loop;
 workbook.sheets( s ).rows.delete();
 workbook.sheets( s ).widths.delete();
 workbook.sheets( s ).autofilters.delete();
 workbook.sheets( s ).hyperlinks.delete();
 workbook.sheets( s ).col_fmts.delete();
 workbook.sheets( s ).row_fmts.delete();
 workbook.sheets( s ).comments.delete();
 workbook.sheets( s ).mergecells.delete();
 workbook.sheets( s ).validations.delete();
 end loop;
 workbook.strings.delete();
 workbook.str_ind.delete();
 workbook.fonts.delete();
 workbook.fills.delete();
 workbook.borders.delete();
 workbook.numFmts.delete();
 workbook.cellXfs.delete();
 workbook.defined_names.delete();
 workbook := null;
 end;
 --
 procedure new_sheet( p_sheetname varchar2 := null )
 is
 t_nr pls_integer := workbook.sheets.count() + 1;
 t_ind pls_integer;
 begin
 workbook.sheets( t_nr ).name := nvl( dbms_xmlgen.convert( translate( p_sheetname, 'a/\[]*:?', 'a' ) ), 'Sheet' || t_nr );
 if workbook.strings.count() = 0
 then
 workbook.str_cnt := 0;
 end if;
 if workbook.fonts.count() = 0
 then
 t_ind := get_font( 'Calibri' );
 end if;
 if workbook.fills.count() = 0
 then
 t_ind := get_fill( 'none' );
 t_ind := get_fill( 'gray125' );
 end if;
 if workbook.borders.count() = 0
 then
 t_ind := get_border( '', '', '', '' );
 end if;
 end;
 --
 procedure set_col_width
 ( p_sheet pls_integer
 , p_col pls_integer
 , p_format varchar2
 )
 is
 t_width number;
 t_nr_chr pls_integer;
 begin
 if p_format is null
 then
 return;
 end if;
 if instr( p_format, ';' ) > 0
 then
 t_nr_chr := length( translate( substr( p_format, 1, instr( p_format, ';' ) - 1 ), 'a\"', 'a' ) );
 else
 t_nr_chr := length( translate( p_format, 'a\"', 'a' ) );
 end if;
 t_width := trunc( ( t_nr_chr * 7 + 5 ) / 7 * 256 ) / 256; -- assume default 11 point Calibri
 if workbook.sheets( p_sheet ).widths.exists( p_col )
 then
 workbook.sheets( p_sheet ).widths( p_col ) :=
 greatest( workbook.sheets( p_sheet ).widths( p_col )
 , t_width
 );
 else
 workbook.sheets( p_sheet ).widths( p_col ) := greatest( t_width, 8.43 );
 end if;
 end;
 --
 function OraFmt2Excel( p_format varchar2 := null )
 return varchar2
 is
 t_format varchar2(1000) := substr( p_format, 1, 1000 );
 begin
 t_format := replace( replace( t_format, 'hh24', 'hh' ), 'hh12', 'hh' );
 t_format := replace( t_format, 'mi', 'mm' );
 t_format := replace( replace( replace( t_format, 'AM', '~~' ), 'PM', '~~' ), '~~', 'AM/PM' );
 t_format := replace( replace( replace( t_format, 'am', '~~' ), 'pm', '~~' ), '~~', 'AM/PM' );
 t_format := replace( replace( t_format, 'day', 'DAY' ), 'DAY', 'dddd' );
 t_format := replace( replace( t_format, 'dy', 'DY' ), 'DAY', 'ddd' );
 t_format := replace( replace( t_format, 'RR', 'RR' ), 'RR', 'YY' );
 t_format := replace( replace( t_format, 'month', 'MONTH' ), 'MONTH', 'mmmm' );
 t_format := replace( replace( t_format, 'mon', 'MON' ), 'MON', 'mmm' );
 return t_format;
 end;
 --
 function get_numFmt( p_format varchar2 := null )
 return pls_integer
 is
 t_cnt pls_integer;
 t_numFmtId pls_integer;
 begin
 if p_format is null
 then
 return 0;
 end if;
 t_cnt := workbook.numFmts.count();
 for i in 1 .. t_cnt
 loop
 if workbook.numFmts( i ).formatCode = p_format
 then
 t_numFmtId := workbook.numFmts( i ).numFmtId;
 exit;
 end if;
 end loop;
 if t_numFmtId is null
 then
 t_numFmtId := case when t_cnt = 0 then 164 else workbook.numFmts( t_cnt ).numFmtId + 1 end;
 t_cnt := t_cnt + 1;
 workbook.numFmts( t_cnt ).numFmtId := t_numFmtId;
 workbook.numFmts( t_cnt ).formatCode := p_format;
 workbook.numFmtIndexes( t_numFmtId ) := t_cnt;
 end if;
 return t_numFmtId;
 end;
 --
 function get_font
 ( p_name varchar2
 , p_family pls_integer := 2
 , p_fontsize number := 11
 , p_theme pls_integer := 1
 , p_underline boolean := false
 , p_italic boolean := false
 , p_bold boolean := false
 , p_rgb varchar2 := null -- this is a hex ALPHA Red Green Blue value
 )
 return pls_integer
 is
 t_ind pls_integer;
 begin
 if workbook.fonts.count() > 0
 then
 for f in 0 .. workbook.fonts.count() - 1
 loop
 if ( workbook.fonts( f ).name = p_name
 and workbook.fonts( f ).family = p_family
 and workbook.fonts( f ).fontsize = p_fontsize
 and workbook.fonts( f ).theme = p_theme
 and workbook.fonts( f ).underline = p_underline
 and workbook.fonts( f ).italic = p_italic
 and workbook.fonts( f ).bold = p_bold
 and ( workbook.fonts( f ).rgb = p_rgb
 or ( workbook.fonts( f ).rgb is null and p_rgb is null )
 )
 )
 then
 return f;
 end if;
 end loop;
 end if;
 t_ind := workbook.fonts.count();
 workbook.fonts( t_ind ).name := p_name;
 workbook.fonts( t_ind ).family := p_family;
 workbook.fonts( t_ind ).fontsize := p_fontsize;
 workbook.fonts( t_ind ).theme := p_theme;
 workbook.fonts( t_ind ).underline := p_underline;
 workbook.fonts( t_ind ).italic := p_italic;
 workbook.fonts( t_ind ).bold := p_bold;
 workbook.fonts( t_ind ).rgb := p_rgb;
 return t_ind;
 end;
 --
 function get_fill
 ( p_patternType varchar2
 , p_fgRGB varchar2 := null
 )
 return pls_integer
 is
 t_ind pls_integer;
 begin
 if workbook.fills.count() > 0
 then
 for f in 0 .. workbook.fills.count() - 1
 loop
 if ( workbook.fills( f ).patternType = p_patternType
 and nvl( workbook.fills( f ).fgRGB, 'x' ) = nvl( upper( p_fgRGB ), 'x' )
 )
 then
 return f;
 end if;
 end loop;
 end if;
 t_ind := workbook.fills.count();
 workbook.fills( t_ind ).patternType := p_patternType;
 workbook.fills( t_ind ).fgRGB := upper( p_fgRGB );
 return t_ind;
 end;
 --
 function get_border
 ( p_top varchar2 := 'thin'
 , p_bottom varchar2 := 'thin'
 , p_left varchar2 := 'thin'
 , p_right varchar2 := 'thin'
 )
 return pls_integer
 is
 t_ind pls_integer;
 begin
 if workbook.borders.count() > 0
 then
 for b in 0 .. workbook.borders.count() - 1
 loop
 if ( nvl( workbook.borders( b ).top, 'x' ) = nvl( p_top, 'x' )
 and nvl( workbook.borders( b ).bottom, 'x' ) = nvl( p_bottom, 'x' )
 and nvl( workbook.borders( b ).left, 'x' ) = nvl( p_left, 'x' )
 and nvl( workbook.borders( b ).right, 'x' ) = nvl( p_right, 'x' )
 )
 then
 return b;
 end if;
 end loop;
 end if;
 t_ind := workbook.borders.count();
 workbook.borders( t_ind ).top := p_top;
 workbook.borders( t_ind ).bottom := p_bottom;
 workbook.borders( t_ind ).left := p_left;
 workbook.borders( t_ind ).right := p_right;
 return t_ind;
 end;
 --
 function get_alignment
 ( p_vertical varchar2 := null
 , p_horizontal varchar2 := null
 , p_wrapText boolean := null
 )
 return tp_alignment
 is
 t_rv tp_alignment;
 begin
 t_rv.vertical := p_vertical;
 t_rv.horizontal := p_horizontal;
 t_rv.wrapText := p_wrapText;
 return t_rv;
 end;
 --
 function get_XfId
 ( p_sheet pls_integer
 , p_col pls_integer
 , p_row pls_integer
 , p_numFmtId pls_integer := null
 , p_fontId pls_integer := null
 , p_fillId pls_integer := null
 , p_borderId pls_integer := null
 , p_alignment tp_alignment := null
 )
 return varchar2
 is
 t_cnt pls_integer;
 t_XfId pls_integer;
 t_XF tp_XF_fmt;
 t_col_XF tp_XF_fmt;
 t_row_XF tp_XF_fmt;
 begin
 if workbook.sheets( p_sheet ).col_fmts.exists( p_col )
 then
 t_col_XF := workbook.sheets( p_sheet ).col_fmts( p_col );
 end if;
 if workbook.sheets( p_sheet ).row_fmts.exists( p_row )
 then
 t_row_XF := workbook.sheets( p_sheet ).row_fmts( p_row );
 end if;
 t_XF.numFmtId := coalesce( p_numFmtId, t_col_XF.numFmtId, t_row_XF.numFmtId, 0 );
 t_XF.fontId := coalesce( p_fontId, t_col_XF.fontId, t_row_XF.fontId, 0 );
 t_XF.fillId := coalesce( p_fillId, t_col_XF.fillId, t_row_XF.fillId, 0 );
 t_XF.borderId := coalesce( p_borderId, t_col_XF.borderId, t_row_XF.borderId, 0 );
 t_XF.alignment := coalesce( p_alignment, t_col_XF.alignment, t_row_XF.alignment );
 if ( t_XF.numFmtId + t_XF.fontId + t_XF.fillId + t_XF.borderId = 0
 and t_XF.alignment.vertical is null
 and t_XF.alignment.horizontal is null
 and not nvl( t_XF.alignment.wrapText, false )
 )
 then
 return '';
 end if;
 if t_XF.numFmtId > 0
 then
 set_col_width( p_sheet, p_col, workbook.numFmts( workbook.numFmtIndexes( t_XF.numFmtId ) ).formatCode );
 end if;
 t_cnt := workbook.cellXfs.count();
 for i in 1 .. t_cnt
 loop
 if ( workbook.cellXfs( i ).numFmtId = t_XF.numFmtId
 and workbook.cellXfs( i ).fontId = t_XF.fontId
 and workbook.cellXfs( i ).fillId = t_XF.fillId
 and workbook.cellXfs( i ).borderId = t_XF.borderId
 and nvl( workbook.cellXfs( i ).alignment.vertical, 'x' ) = nvl( t_XF.alignment.vertical, 'x' )
 and nvl( workbook.cellXfs( i ).alignment.horizontal, 'x' ) = nvl( t_XF.alignment.horizontal, 'x' )
 and nvl( workbook.cellXfs( i ).alignment.wrapText, false ) = nvl( t_XF.alignment.wrapText, false )
 )
 then
 t_XfId := i;
 exit;
 end if;
 end loop;
 if t_XfId is null
 then
 t_cnt := t_cnt + 1;
 t_XfId := t_cnt;
 workbook.cellXfs( t_cnt ) := t_XF;
 end if;
 return 's="' || t_XfId || '"';
 end;
 --
 procedure cell
 ( p_col pls_integer
 , p_row pls_integer
 , p_value number
 , p_numFmtId pls_integer := null
 , p_fontId pls_integer := null
 , p_fillId pls_integer := null
 , p_borderId pls_integer := null
 , p_alignment tp_alignment := null
 , p_sheet pls_integer := null
 )
 is
 t_sheet pls_integer := nvl( p_sheet, workbook.sheets.count() );
 begin
 workbook.sheets( t_sheet ).rows( p_row )( p_col ).value := p_value;
 workbook.sheets( t_sheet ).rows( p_row )( p_col ).style := null;
 workbook.sheets( t_sheet ).rows( p_row )( p_col ).style := get_XfId( t_sheet, p_col, p_row, p_numFmtId, p_fontId, p_fillId, p_borderId, p_alignment );
 end;
 --
 function add_string( p_string varchar2 )
 return pls_integer
 is
 t_cnt pls_integer;
 begin
 if workbook.strings.exists( p_string )
 then
 t_cnt := workbook.strings( p_string );
 else
 t_cnt := workbook.strings.count();
 workbook.str_ind( t_cnt ) := p_string;
 workbook.strings( nvl( p_string, '' ) ) := t_cnt;
 end if;
 workbook.str_cnt := workbook.str_cnt + 1;
 return t_cnt;
 end;
 --
 procedure cell
 ( p_col pls_integer
 , p_row pls_integer
 , p_value varchar2
 , p_numFmtId pls_integer := null
 , p_fontId pls_integer := null
 , p_fillId pls_integer := null
 , p_borderId pls_integer := null
 , p_alignment tp_alignment := null
 , p_sheet pls_integer := null
 )
 is
 t_sheet pls_integer := nvl( p_sheet, workbook.sheets.count() );
 t_alignment tp_alignment := p_alignment;
 begin
 workbook.sheets( t_sheet ).rows( p_row )( p_col ).value := add_string( p_value );
 if t_alignment.wrapText is null and instr( p_value, chr(13) ) > 0
 then
 t_alignment.wrapText := true;
 end if;
 workbook.sheets( t_sheet ).rows( p_row )( p_col ).style := 't="s" ' || get_XfId( t_sheet, p_col, p_row, p_numFmtId, p_fontId, p_fillId, p_borderId, t_alignment );
 end;
 --
 procedure cell
 ( p_col pls_integer
 , p_row pls_integer
 , p_value date
 , p_numFmtId pls_integer := null
 , p_fontId pls_integer := null
 , p_fillId pls_integer := null
 , p_borderId pls_integer := null
 , p_alignment tp_alignment := null
 , p_sheet pls_integer := null
 )
 is
 t_numFmtId pls_integer := p_numFmtId;
 t_sheet pls_integer := nvl( p_sheet, workbook.sheets.count() );
 begin
 workbook.sheets( t_sheet ).rows( p_row )( p_col ).value := p_value - to_date('01-01-1904','DD-MM-YYYY');
 if t_numFmtId is null
 and not ( workbook.sheets( t_sheet ).col_fmts.exists( p_col )
 and workbook.sheets( t_sheet ).col_fmts( p_col ).numFmtId is not null
 )
 and not ( workbook.sheets( t_sheet ).row_fmts.exists( p_row )
 and workbook.sheets( t_sheet ).row_fmts( p_row ).numFmtId is not null
 )
 then
 t_numFmtId := get_numFmt( 'dd/mm/yyyy' );
 end if;
 workbook.sheets( t_sheet ).rows( p_row )( p_col ).style := get_XfId( t_sheet, p_col, p_row, t_numFmtId, p_fontId, p_fillId, p_borderId, p_alignment );
 end;
 --
 procedure hyperlink
 ( p_col pls_integer
 , p_row pls_integer
 , p_url varchar2
 , p_value varchar2 := null
 , p_sheet pls_integer := null
 )
 is
 t_ind pls_integer;
 t_sheet pls_integer := nvl( p_sheet, workbook.sheets.count() );
 begin
 workbook.sheets( t_sheet ).rows( p_row )( p_col ).value := add_string( nvl( p_value, p_url ) );
 workbook.sheets( t_sheet ).rows( p_row )( p_col ).style := 't="s" ' || get_XfId( t_sheet, p_col, p_row, '', get_font( 'Calibri', p_theme => 10, p_underline => true ) );
 t_ind := workbook.sheets( t_sheet ).hyperlinks.count() + 1;
 workbook.sheets( t_sheet ).hyperlinks( t_ind ).cell := alfan_col( p_col ) || p_row;
 workbook.sheets( t_sheet ).hyperlinks( t_ind ).url := p_url;
 end;
 --
 procedure comment
 ( p_col pls_integer
 , p_row pls_integer
 , p_text varchar2
 , p_author varchar2 := null
 , p_width pls_integer := 150
 , p_height pls_integer := 100
 , p_sheet pls_integer := null
 )
 is
 t_ind pls_integer;
 t_sheet pls_integer := nvl( p_sheet, workbook.sheets.count() );
 begin
 t_ind := workbook.sheets( t_sheet ).comments.count() + 1;
 workbook.sheets( t_sheet ).comments( t_ind ).row := p_row;
 workbook.sheets( t_sheet ).comments( t_ind ).column := p_col;
 workbook.sheets( t_sheet ).comments( t_ind ).text := dbms_xmlgen.convert( p_text );
 workbook.sheets( t_sheet ).comments( t_ind ).author := dbms_xmlgen.convert( p_author );
 workbook.sheets( t_sheet ).comments( t_ind ).width := p_width;
 workbook.sheets( t_sheet ).comments( t_ind ).height := p_height;
 end;
 --
 procedure mergecells
 ( p_tl_col pls_integer -- top left
 , p_tl_row pls_integer
 , p_br_col pls_integer -- bottom right
 , p_br_row pls_integer
 , p_sheet pls_integer := null
 )
 is
 t_ind pls_integer;
 t_sheet pls_integer := nvl( p_sheet, workbook.sheets.count() );
 begin
 t_ind := workbook.sheets( t_sheet ).mergecells.count() + 1;
 workbook.sheets( t_sheet ).mergecells( t_ind ) := alfan_col( p_tl_col ) || p_tl_row || ':' || alfan_col( p_br_col ) || p_br_row;
 end;
 --
 procedure add_validation
 ( p_type varchar2
 , p_sqref varchar2
 , p_style varchar2 := 'stop' -- stop, warning, information
 , p_formula1 varchar2 := null
 , p_formula2 varchar2 := null
 , p_title varchar2 := null
 , p_prompt varchar := null
 , p_show_error boolean := false
 , p_error_title varchar2 := null
 , p_error_txt varchar2 := null
 , p_sheet pls_integer := null
 )
 is
 t_ind pls_integer;
 t_sheet pls_integer := nvl( p_sheet, workbook.sheets.count() );
 begin
 t_ind := workbook.sheets( t_sheet ).validations.count() + 1;
 workbook.sheets( t_sheet ).validations( t_ind ).type := p_type;
 workbook.sheets( t_sheet ).validations( t_ind ).errorstyle := p_style;
 workbook.sheets( t_sheet ).validations( t_ind ).sqref := p_sqref;
 workbook.sheets( t_sheet ).validations( t_ind ).formula1 := p_formula1;
 workbook.sheets( t_sheet ).validations( t_ind ).error_title := p_error_title;
 workbook.sheets( t_sheet ).validations( t_ind ).error_txt := p_error_txt;
 workbook.sheets( t_sheet ).validations( t_ind ).title := p_title;
 workbook.sheets( t_sheet ).validations( t_ind ).prompt := p_prompt;
 workbook.sheets( t_sheet ).validations( t_ind ).showerrormessage := p_show_error;
 end;
 --
 procedure list_validation
 ( p_sqref_col pls_integer
 , p_sqref_row pls_integer
 , p_tl_col pls_integer -- top left
 , p_tl_row pls_integer
 , p_br_col pls_integer -- bottom right
 , p_br_row pls_integer
 , p_style varchar2 := 'stop' -- stop, warning, information
 , p_title varchar2 := null
 , p_prompt varchar := null
 , p_show_error boolean := false
 , p_error_title varchar2 := null
 , p_error_txt varchar2 := null
 , p_sheet pls_integer := null
 )
 is
 begin
 add_validation( 'list'
 , alfan_col( p_sqref_col ) || p_sqref_row
 , p_style => lower( p_style )
 , p_formula1 => '$' || alfan_col( p_tl_col ) || '$' || p_tl_row || ':$' || alfan_col( p_br_col ) || '$' || p_br_row
 , p_title => p_title
 , p_prompt => p_prompt
 , p_show_error => p_show_error
 , p_error_title => p_error_title
 , p_error_txt => p_error_txt
 , p_sheet => p_sheet
 );
 end;
 --
 procedure list_validation
 ( p_sqref_col pls_integer
 , p_sqref_row pls_integer
 , p_defined_name varchar2
 , p_style varchar2 := 'stop' -- stop, warning, information
 , p_title varchar2 := null
 , p_prompt varchar := null
 , p_show_error boolean := false
 , p_error_title varchar2 := null
 , p_error_txt varchar2 := null
 , p_sheet pls_integer := null
 )
 is
 begin
 add_validation( 'list'
 , alfan_col( p_sqref_col ) || p_sqref_row
 , p_style => lower( p_style )
 , p_formula1 => p_defined_name
 , p_title => p_title
 , p_prompt => p_prompt
 , p_show_error => p_show_error
 , p_error_title => p_error_title
 , p_error_txt => p_error_txt
 , p_sheet => p_sheet
 );
 end;
 --
 procedure defined_name
 ( p_tl_col pls_integer -- top left
 , p_tl_row pls_integer
 , p_br_col pls_integer -- bottom right
 , p_br_row pls_integer
 , p_name varchar2
 , p_sheet pls_integer := null
 , p_localsheet pls_integer := null
 )
 is
 t_ind pls_integer;
 t_sheet pls_integer := nvl( p_sheet, workbook.sheets.count() );
 begin
 t_ind := workbook.defined_names.count() + 1;
 workbook.defined_names( t_ind ).name := p_name;
 workbook.defined_names( t_ind ).ref := 'Sheet' || t_sheet || '!$' || alfan_col( p_tl_col ) || '$' || p_tl_row || ':$' || alfan_col( p_br_col ) || '$' || p_br_row;
 workbook.defined_names( t_ind ).sheet := p_localsheet;
 end;
 --
 procedure set_column_width
 ( p_col pls_integer
 , p_width number
 , p_sheet pls_integer := null
 )
 is
 begin
 workbook.sheets( nvl( p_sheet, workbook.sheets.count() ) ).widths( p_col ) := p_width;
 end;
 --
 procedure set_column
 ( p_col pls_integer
 , p_numFmtId pls_integer := null
 , p_fontId pls_integer := null
 , p_fillId pls_integer := null
 , p_borderId pls_integer := null
 , p_alignment tp_alignment := null
 , p_sheet pls_integer := null
 )
 is
 t_sheet pls_integer := nvl( p_sheet, workbook.sheets.count() );
 begin
 workbook.sheets( t_sheet ).col_fmts( p_col ).numFmtId := p_numFmtId;
 workbook.sheets( t_sheet ).col_fmts( p_col ).fontId := p_fontId;
 workbook.sheets( t_sheet ).col_fmts( p_col ).fillId := p_fillId;
 workbook.sheets( t_sheet ).col_fmts( p_col ).borderId := p_borderId;
 workbook.sheets( t_sheet ).col_fmts( p_col ).alignment := p_alignment;
 end;
 --
 procedure set_row
 ( p_row pls_integer
 , p_numFmtId pls_integer := null
 , p_fontId pls_integer := null
 , p_fillId pls_integer := null
 , p_borderId pls_integer := null
 , p_alignment tp_alignment := null
 , p_sheet pls_integer := null
 )
 is
 t_sheet pls_integer := nvl( p_sheet, workbook.sheets.count() );
 begin
 workbook.sheets( t_sheet ).row_fmts( p_row ).numFmtId := p_numFmtId;
 workbook.sheets( t_sheet ).row_fmts( p_row ).fontId := p_fontId;
 workbook.sheets( t_sheet ).row_fmts( p_row ).fillId := p_fillId;
 workbook.sheets( t_sheet ).row_fmts( p_row ).borderId := p_borderId;
 workbook.sheets( t_sheet ).row_fmts( p_row ).alignment := p_alignment;
 end;
 --
 procedure freeze_rows
 ( p_nr_rows pls_integer := 1
 , p_sheet pls_integer := null
 )
 is
 t_sheet pls_integer := nvl( p_sheet, workbook.sheets.count() );
 begin
 workbook.sheets( t_sheet ).freeze_cols := null;
 workbook.sheets( t_sheet ).freeze_rows := p_nr_rows;
 end;
 --
 procedure freeze_cols
 ( p_nr_cols pls_integer := 1
 , p_sheet pls_integer := null
 )
 is
 t_sheet pls_integer := nvl( p_sheet, workbook.sheets.count() );
 begin
 workbook.sheets( t_sheet ).freeze_rows := null;
 workbook.sheets( t_sheet ).freeze_cols := p_nr_cols;
 end;
 --
 procedure freeze_pane
 ( p_col pls_integer
 , p_row pls_integer
 , p_sheet pls_integer := null
 )
 is
 t_sheet pls_integer := nvl( p_sheet, workbook.sheets.count() );
 begin
 workbook.sheets( t_sheet ).freeze_rows := p_row;
 workbook.sheets( t_sheet ).freeze_cols := p_col;
 end;
 --
 procedure set_autofilter
 ( p_column_start pls_integer := null
 , p_column_end pls_integer := null
 , p_row_start pls_integer := null
 , p_row_end pls_integer := null
 , p_sheet pls_integer := null
 )
 is
 t_ind pls_integer;
 t_sheet pls_integer := nvl( p_sheet, workbook.sheets.count() );
 begin
 t_ind := 1;
 workbook.sheets( t_sheet ).autofilters( t_ind ).column_start := p_column_start;
 workbook.sheets( t_sheet ).autofilters( t_ind ).column_end := p_column_end;
 workbook.sheets( t_sheet ).autofilters( t_ind ).row_start := p_row_start;
 workbook.sheets( t_sheet ).autofilters( t_ind ).row_end := p_row_end;
 defined_name
 ( p_column_start
 , p_row_start
 , p_column_end
 , p_row_end
 , '_xlnm._FilterDatabase'
 , t_sheet
 , t_sheet - 1
 );
 end;
 --
 /*
 procedure add1xml
 ( p_excel in out nocopy blob
 , p_filename varchar2
 , p_xml clob
 )
 is
 t_tmp blob;
 c_step constant number := 24396;
 begin
 dbms_lob.createtemporary( t_tmp, true );
 for i in 0 .. trunc( length( p_xml ) / c_step )
 loop
 dbms_lob.append( t_tmp, utl_i18n.string_to_raw( substr( p_xml, i * c_step + 1, c_step ), 'AL32UTF8' ) );
 end loop;
 add1file( p_excel, p_filename, t_tmp );
 dbms_lob.freetemporary( t_tmp );
 end;
 */
 --
 procedure add1xml
 ( p_excel in out nocopy blob
 , p_filename varchar2
 , p_xml clob
 )
 is
 t_tmp blob;
 dest_offset integer := 1;
 src_offset integer := 1;
 lang_context integer;
 warning integer;
 begin
 lang_context := dbms_lob.DEFAULT_LANG_CTX;
 dbms_lob.createtemporary( t_tmp, true );
 dbms_lob.converttoblob
 ( t_tmp
 , p_xml
 , dbms_lob.lobmaxsize
 , dest_offset
 , src_offset
 , nls_charset_id( 'AL32UTF8' )
 , lang_context
 , warning
 );
 add1file( p_excel, p_filename, t_tmp );
 dbms_lob.freetemporary( t_tmp );
 end;
 --
 function finish
 return blob
 is
 t_excel blob;
 t_xxx clob;
 t_tmp varchar2(32767 char);
 t_str varchar2(32767 char);
 t_c number;
 t_h number;
 t_w number;
 t_cw number;
 t_cell varchar2(1000 char);
 t_row_ind pls_integer;
 t_col_min pls_integer;
 t_col_max pls_integer;
 t_col_ind pls_integer;
 t_len pls_integer;
 ts timestamp := systimestamp;
 begin
 dbms_lob.createtemporary( t_excel, true );
 t_xxx := '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
 <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
 <Default Extension="xml" ContentType="application/xml"/>
 <Default Extension="vml" ContentType="application/vnd.openxmlformats-officedocument.vmlDrawing"/>
 <Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>';
 for s in 1 .. workbook.sheets.count()
 loop
 t_xxx := t_xxx || '
 <Override PartName="/xl/worksheets/sheet' || s || '.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>';
 end loop;
 t_xxx := t_xxx || '
 <Override PartName="/xl/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>
 <Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>
 <Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>
 <Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>
 <Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>';
 for s in 1 .. workbook.sheets.count()
 loop
 if workbook.sheets( s ).comments.count() > 0
 then
 t_xxx := t_xxx || '
 <Override PartName="/xl/comments' || s || '.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml"/>';
 end if;
 end loop;
 t_xxx := t_xxx || '
 </Types>';
 add1xml( t_excel, '[Content_Types].xml', t_xxx );
 t_xxx := '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <dc:creator>' || sys_context( 'userenv', 'os_user' ) || '</dc:creator>
 <cp:lastModifiedBy>' || sys_context( 'userenv', 'os_user' ) || '</cp:lastModifiedBy>
 <dcterms:created xsi:type="dcterms:W3CDTF">' || to_char( current_timestamp, 'yyyy-mm-dd"T"hh24:mi:ssTZH:TZM' ) || '</dcterms:created>
 <dcterms:modified xsi:type="dcterms:W3CDTF">' || to_char( current_timestamp, 'yyyy-mm-dd"T"hh24:mi:ssTZH:TZM' ) || '</dcterms:modified>
 </cp:coreProperties>';
 add1xml( t_excel, 'docProps/core.xml', t_xxx );
 t_xxx := '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">
 <Application>Microsoft Excel</Application>
 <DocSecurity>0</DocSecurity>
 <ScaleCrop>false</ScaleCrop>
 <HeadingPairs>
 <vt:vector size="2" baseType="variant">
 <vt:variant>
 <vt:lpstr>Worksheets</vt:lpstr>
 </vt:variant>
 <vt:variant>
 <vt:i4>' || workbook.sheets.count() || '</vt:i4>
 </vt:variant>
 </vt:vector>
 </HeadingPairs>
 <TitlesOfParts>
 <vt:vector size="' || workbook.sheets.count() || '" baseType="lpstr">';
 for s in 1 .. workbook.sheets.count()
 loop
 t_xxx := t_xxx || '
 <vt:lpstr>' || workbook.sheets( s ).name || '</vt:lpstr>';
 end loop;
 t_xxx := t_xxx || '</vt:vector>
 </TitlesOfParts>
 <LinksUpToDate>false</LinksUpToDate>
 <SharedDoc>false</SharedDoc>
 <HyperlinksChanged>false</HyperlinksChanged>
 <AppVersion>14.0300</AppVersion>
 </Properties>';
 add1xml( t_excel, 'docProps/app.xml', t_xxx );
 t_xxx := '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
 <Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>
 <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
 <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
 </Relationships>';
 add1xml( t_excel, '_rels/.rels', t_xxx );
 t_xxx := '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">';
 if workbook.numFmts.count() > 0
 then
 t_xxx := t_xxx || '<numFmts count="' || workbook.numFmts.count() || '">';
 for n in 1 .. workbook.numFmts.count()
 loop
 t_xxx := t_xxx || '<numFmt numFmtId="' || workbook.numFmts( n ).numFmtId || '" formatCode="' || workbook.numFmts( n ).formatCode || '"/>';
 end loop;
 t_xxx := t_xxx || '</numFmts>';
 end if;
 t_xxx := t_xxx || '<fonts count="' || workbook.fonts.count() || '" x14ac:knownFonts="1">';
 for f in 0 .. workbook.fonts.count() - 1
 loop
 t_xxx := t_xxx || '<font>' ||
 case when workbook.fonts( f ).bold then '<b/>' end ||
 case when workbook.fonts( f ).italic then '<i/>' end ||
 case when workbook.fonts( f ).underline then '<u/>' end ||
 '<sz val="' || to_char( workbook.fonts( f ).fontsize, 'TM9', 'NLS_NUMERIC_CHARACTERS=.,' ) || '"/>
 <color ' || case when workbook.fonts( f ).rgb is not null
 then 'rgb="' || workbook.fonts( f ).rgb
 else 'theme="' || workbook.fonts( f ).theme
 end || '"/>
 <name val="' || workbook.fonts( f ).name || '"/>
 <family val="' || workbook.fonts( f ).family || '"/>
 <scheme val="none"/>
 </font>';
 end loop;
 t_xxx := t_xxx || '</fonts>
 <fills count="' || workbook.fills.count() || '">';
 for f in 0 .. workbook.fills.count() - 1
 loop
 t_xxx := t_xxx || '<fill><patternFill patternType="' || workbook.fills( f ).patternType || '">' ||
 case when workbook.fills( f ).fgRGB is not null then '<fgColor rgb="' || workbook.fills( f ).fgRGB || '"/>' end ||
 '</patternFill></fill>';
 end loop;
 t_xxx := t_xxx || '</fills>
 <borders count="' || workbook.borders.count() || '">';
 for b in 0 .. workbook.borders.count() - 1
 loop
 t_xxx := t_xxx || '<border>' ||
 case when workbook.borders( b ).left is null then '<left/>' else '<left style="' || workbook.borders( b ).left || '"/>' end ||
 case when workbook.borders( b ).right is null then '<right/>' else '<right style="' || workbook.borders( b ).right || '"/>' end ||
 case when workbook.borders( b ).top is null then '<top/>' else '<top style="' || workbook.borders( b ).top || '"/>' end ||
 case when workbook.borders( b ).bottom is null then '<bottom/>' else '<bottom style="' || workbook.borders( b ).bottom || '"/>' end ||
 '</border>';
 end loop;
 t_xxx := t_xxx || '</borders>
 <cellStyleXfs count="1">
 <xf numFmtId="0" fontId="0" fillId="0" borderId="0"/>
 </cellStyleXfs>
 <cellXfs count="' || ( workbook.cellXfs.count() + 1 ) || '">
 <xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>';
 for x in 1 .. workbook.cellXfs.count()
 loop
 t_xxx := t_xxx || '<xf numFmtId="' || workbook.cellXfs( x ).numFmtId || '" fontId="' || workbook.cellXfs( x ).fontId || '" fillId="' || workbook.cellXfs( x ).fillId || '" borderId="' || workbook.cellXfs( x ).borderId || '">';
 if ( workbook.cellXfs( x ).alignment.horizontal is not null
 or workbook.cellXfs( x ).alignment.vertical is not null
 or workbook.cellXfs( x ).alignment.wrapText
 )
 then
 t_xxx := t_xxx || '<alignment' ||
 case when workbook.cellXfs( x ).alignment.horizontal is not null then ' horizontal="' || workbook.cellXfs( x ).alignment.horizontal || '"' end ||
 case when workbook.cellXfs( x ).alignment.vertical is not null then ' vertical="' || workbook.cellXfs( x ).alignment.vertical || '"' end ||
 case when workbook.cellXfs( x ).alignment.wrapText then ' wrapText="true"' end || '/>';
 end if;
 t_xxx := t_xxx || '</xf>';
 end loop;
 t_xxx := t_xxx || '</cellXfs>
 <cellStyles count="1">
 <cellStyle name="Normal" xfId="0" builtinId="0"/>
 </cellStyles>
 <dxfs count="0"/>
 <tableStyles count="0" defaultTableStyle="TableStyleMedium2" defaultPivotStyle="PivotStyleLight16"/>
 <extLst>
 <ext uri="{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main">
 <x14:slicerStyles defaultSlicerStyle="SlicerStyleLight1"/>
 </ext>
 </extLst>
 </styleSheet>';
 add1xml( t_excel, 'xl/styles.xml', t_xxx );
 t_xxx := '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
 <fileVersion appName="xl" lastEdited="5" lowestEdited="5" rupBuild="9302"/>
 <workbookPr date1904="true" defaultThemeVersion="124226"/>
 <bookViews>
 <workbookView xWindow="120" yWindow="45" windowWidth="19155" windowHeight="4935"/>
 </bookViews>
 <sheets>';
 for s in 1 .. workbook.sheets.count()
 loop
 t_xxx := t_xxx || '
 <sheet name="' || workbook.sheets( s ).name || '" sheetId="' || s || '" r:id="rId' || ( 9 + s ) || '"/>';
 end loop;
 t_xxx := t_xxx || '</sheets>';
 if workbook.defined_names.count() > 0
 then
 t_xxx := t_xxx || '<definedNames>';
 for s in 1 .. workbook.defined_names.count()
 loop
 t_xxx := t_xxx || '
 <definedName name="' || workbook.defined_names( s ).name || '"' ||
 case when workbook.defined_names( s ).sheet is not null then ' localSheetId="' || to_char( workbook.defined_names( s ).sheet ) || '"' end ||
 '>' || workbook.defined_names( s ).ref || '</definedName>';
 end loop;
 t_xxx := t_xxx || '</definedNames>';
 end if;
 t_xxx := t_xxx || '<calcPr calcId="144525"/></workbook>';
 add1xml( t_excel, 'xl/workbook.xml', t_xxx );
 t_xxx := '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">
 <a:themeElements>
 <a:clrScheme name="Office">
 <a:dk1>
 <a:sysClr val="windowText" lastClr="000000"/>
 </a:dk1>
 <a:lt1>
 <a:sysClr val="window" lastClr="FFFFFF"/>
 </a:lt1>
 <a:dk2>
 <a:srgbClr val="1F497D"/>
 </a:dk2>
 <a:lt2>
 <a:srgbClr val="EEECE1"/>
 </a:lt2>
 <a:accent1>
 <a:srgbClr val="4F81BD"/>
 </a:accent1>
 <a:accent2>
 <a:srgbClr val="C0504D"/>
 </a:accent2>
 <a:accent3>
 <a:srgbClr val="9BBB59"/>
 </a:accent3>
 <a:accent4>
 <a:srgbClr val="8064A2"/>
 </a:accent4>
 <a:accent5>
 <a:srgbClr val="4BACC6"/>
 </a:accent5>
 <a:accent6>
 <a:srgbClr val="F79646"/>
 </a:accent6>
 <a:hlink>
 <a:srgbClr val="0000FF"/>
 </a:hlink>
 <a:folHlink>
 <a:srgbClr val="800080"/>
 </a:folHlink>
 </a:clrScheme>
 <a:fontScheme name="Office">
 <a:majorFont>
 <a:latin typeface="Cambria"/>
 <a:ea typeface=""/>
 <a:cs typeface=""/>
 <a:font script="Jpan" typeface="MS P????"/>
 <a:font script="Hang" typeface="?? ??"/>
 <a:font script="Hans" typeface="??"/>
 <a:font script="Hant" typeface="????"/>
 <a:font script="Arab" typeface="Times New Roman"/>
 <a:font script="Hebr" typeface="Times New Roman"/>
 <a:font script="Thai" typeface="Tahoma"/>
 <a:font script="Ethi" typeface="Nyala"/>
 <a:font script="Beng" typeface="Vrinda"/>
 <a:font script="Gujr" typeface="Shruti"/>
 <a:font script="Khmr" typeface="MoolBoran"/>
 <a:font script="Knda" typeface="Tunga"/>
 <a:font script="Guru" typeface="Raavi"/>
 <a:font script="Cans" typeface="Euphemia"/>
 <a:font script="Cher" typeface="Plantagenet Cherokee"/>
 <a:font script="Yiii" typeface="Microsoft Yi Baiti"/>
 <a:font script="Tibt" typeface="Microsoft Himalaya"/>
 <a:font script="Thaa" typeface="MV Boli"/>
 <a:font script="Deva" typeface="Mangal"/>
 <a:font script="Telu" typeface="Gautami"/>
 <a:font script="Taml" typeface="Latha"/>
 <a:font script="Syrc" typeface="Estrangelo Edessa"/>
 <a:font script="Orya" typeface="Kalinga"/>
 <a:font script="Mlym" typeface="Kartika"/>
 <a:font script="Laoo" typeface="DokChampa"/>
 <a:font script="Sinh" typeface="Iskoola Pota"/>
 <a:font script="Mong" typeface="Mongolian Baiti"/>
 <a:font script="Viet" typeface="Times New Roman"/>
 <a:font script="Uigh" typeface="Microsoft Uighur"/>
 <a:font script="Geor" typeface="Sylfaen"/>
 </a:majorFont>
 <a:minorFont>
 <a:latin typeface="Calibri"/>
 <a:ea typeface=""/>
 <a:cs typeface=""/>
 <a:font script="Jpan" typeface="MS P????"/>
 <a:font script="Hang" typeface="?? ??"/>
 <a:font script="Hans" typeface="??"/>
 <a:font script="Hant" typeface="????"/>
 <a:font script="Arab" typeface="Arial"/>
 <a:font script="Hebr" typeface="Arial"/>
 <a:font script="Thai" typeface="Tahoma"/>
 <a:font script="Ethi" typeface="Nyala"/>
 <a:font script="Beng" typeface="Vrinda"/>
 <a:font script="Gujr" typeface="Shruti"/>
 <a:font script="Khmr" typeface="DaunPenh"/>
 <a:font script="Knda" typeface="Tunga"/>
 <a:font script="Guru" typeface="Raavi"/>
 <a:font script="Cans" typeface="Euphemia"/>
 <a:font script="Cher" typeface="Plantagenet Cherokee"/>
 <a:font script="Yiii" typeface="Microsoft Yi Baiti"/>
 <a:font script="Tibt" typeface="Microsoft Himalaya"/>
 <a:font script="Thaa" typeface="MV Boli"/>
 <a:font script="Deva" typeface="Mangal"/>
 <a:font script="Telu" typeface="Gautami"/>
 <a:font script="Taml" typeface="Latha"/>
 <a:font script="Syrc" typeface="Estrangelo Edessa"/>
 <a:font script="Orya" typeface="Kalinga"/>
 <a:font script="Mlym" typeface="Kartika"/>
 <a:font script="Laoo" typeface="DokChampa"/>
 <a:font script="Sinh" typeface="Iskoola Pota"/>
 <a:font script="Mong" typeface="Mongolian Baiti"/>
 <a:font script="Viet" typeface="Arial"/>
 <a:font script="Uigh" typeface="Microsoft Uighur"/>
 <a:font script="Geor" typeface="Sylfaen"/>
 </a:minorFont>
 </a:fontScheme>
 <a:fmtScheme name="Office">
 <a:fillStyleLst>
 <a:solidFill>
 <a:schemeClr val="phClr"/>
 </a:solidFill>
 <a:gradFill rotWithShape="1">
 <a:gsLst>
 <a:gs pos="0">
 <a:schemeClr val="phClr">
 <a:tint val="50000"/>
 <a:satMod val="300000"/>
 </a:schemeClr>
 </a:gs>
 <a:gs pos="35000">
 <a:schemeClr val="phClr">
 <a:tint val="37000"/>
 <a:satMod val="300000"/>
 </a:schemeClr>
 </a:gs>
 <a:gs pos="100000">
 <a:schemeClr val="phClr">
 <a:tint val="15000"/>
 <a:satMod val="350000"/>
 </a:schemeClr>
 </a:gs>
 </a:gsLst>
 <a:lin ang="16200000" scaled="1"/>
 </a:gradFill>
 <a:gradFill rotWithShape="1">
 <a:gsLst>
 <a:gs pos="0">
 <a:schemeClr val="phClr">
 <a:shade val="51000"/>
 <a:satMod val="130000"/>
 </a:schemeClr>
 </a:gs>
 <a:gs pos="80000">
 <a:schemeClr val="phClr">
 <a:shade val="93000"/>
 <a:satMod val="130000"/>
 </a:schemeClr>
 </a:gs>
 <a:gs pos="100000">
 <a:schemeClr val="phClr">
 <a:shade val="94000"/>
 <a:satMod val="135000"/>
 </a:schemeClr>
 </a:gs>
 </a:gsLst>
 <a:lin ang="16200000" scaled="0"/>
 </a:gradFill>
 </a:fillStyleLst>
 <a:lnStyleLst>
 <a:ln w="9525" cap="flat" cmpd="sng" algn="ctr">
 <a:solidFill>
 <a:schemeClr val="phClr">
 <a:shade val="95000"/>
 <a:satMod val="105000"/>
 </a:schemeClr>
 </a:solidFill>
 <a:prstDash val="solid"/>
 </a:ln>
 <a:ln w="25400" cap="flat" cmpd="sng" algn="ctr">
 <a:solidFill>
 <a:schemeClr val="phClr"/>
 </a:solidFill>
 <a:prstDash val="solid"/>
 </a:ln>
 <a:ln w="38100" cap="flat" cmpd="sng" algn="ctr">
 <a:solidFill>
 <a:schemeClr val="phClr"/>
 </a:solidFill>
 <a:prstDash val="solid"/>
 </a:ln>
 </a:lnStyleLst>
 <a:effectStyleLst>
 <a:effectStyle>
 <a:effectLst>
 <a:outerShdw blurRad="40000" dist="20000" dir="5400000" rotWithShape="0">
 <a:srgbClr val="000000">
 <a:alpha val="38000"/>
 </a:srgbClr>
 </a:outerShdw>
 </a:effectLst>
 </a:effectStyle>
 <a:effectStyle>
 <a:effectLst>
 <a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0">
 <a:srgbClr val="000000">
 <a:alpha val="35000"/>
 </a:srgbClr>
 </a:outerShdw>
 </a:effectLst>
 </a:effectStyle>
 <a:effectStyle>
 <a:effectLst>
 <a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0">
 <a:srgbClr val="000000">
 <a:alpha val="35000"/>
 </a:srgbClr>
 </a:outerShdw>
 </a:effectLst>
 <a:scene3d>
 <a:camera prst="orthographicFront">
 <a:rot lat="0" lon="0" rev="0"/>
 </a:camera>
 <a:lightRig rig="threePt" dir="t">
 <a:rot lat="0" lon="0" rev="1200000"/>
 </a:lightRig>
 </a:scene3d>
 <a:sp3d>
 <a:bevelT w="63500" h="25400"/>
 </a:sp3d>
 </a:effectStyle>
 </a:effectStyleLst>
 <a:bgFillStyleLst>
 <a:solidFill>
 <a:schemeClr val="phClr"/>
 </a:solidFill>
 <a:gradFill rotWithShape="1">
 <a:gsLst>
 <a:gs pos="0">
 <a:schemeClr val="phClr">
 <a:tint val="40000"/>
 <a:satMod val="350000"/>
 </a:schemeClr>
 </a:gs>
 <a:gs pos="40000">
 <a:schemeClr val="phClr">
 <a:tint val="45000"/>
 <a:shade val="99000"/>
 <a:satMod val="350000"/>
 </a:schemeClr>
 </a:gs>
 <a:gs pos="100000">
 <a:schemeClr val="phClr">
 <a:shade val="20000"/>
 <a:satMod val="255000"/>
 </a:schemeClr>
 </a:gs>
 </a:gsLst>
 <a:path path="circle">
 <a:fillToRect l="50000" t="-80000" r="50000" b="180000"/>
 </a:path>
 </a:gradFill>
 <a:gradFill rotWithShape="1">
 <a:gsLst>
 <a:gs pos="0">
 <a:schemeClr val="phClr">
 <a:tint val="80000"/>
 <a:satMod val="300000"/>
 </a:schemeClr>
 </a:gs>
 <a:gs pos="100000">
 <a:schemeClr val="phClr">
 <a:shade val="30000"/>
 <a:satMod val="200000"/>
 </a:schemeClr>
 </a:gs>
 </a:gsLst>
 <a:path path="circle">
 <a:fillToRect l="50000" t="50000" r="50000" b="50000"/>
 </a:path>
 </a:gradFill>
 </a:bgFillStyleLst>
 </a:fmtScheme>
 </a:themeElements>
 <a:objectDefaults/>
 <a:extraClrSchemeLst/>
 </a:theme>';
 add1xml( t_excel, 'xl/theme/theme1.xml', t_xxx );
 for s in 1 .. workbook.sheets.count()
 loop
 t_col_min := 16384;
 t_col_max := 1;
 t_row_ind := workbook.sheets( s ).rows.first();
 while t_row_ind is not null
 loop
 t_col_min := least( t_col_min, workbook.sheets( s ).rows( t_row_ind ).first() );
 t_col_max := greatest( t_col_max, workbook.sheets( s ).rows( t_row_ind ).last() );
 t_row_ind := workbook.sheets( s ).rows.next( t_row_ind );
 end loop;
 t_xxx := '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">
 <dimension ref="' || alfan_col( t_col_min ) || workbook.sheets( s ).rows.first() || ':' || alfan_col( t_col_max ) || workbook.sheets( s ).rows.last() || '"/>
 <sheetViews>
 <sheetView' || case when s = 1 then ' tabSelected="1"' end || ' workbookViewId="0">';
 if workbook.sheets( s ).freeze_rows > 0 and workbook.sheets( s ).freeze_cols > 0
 then
 t_xxx := t_xxx || ( '<pane xSplit="' || workbook.sheets( s ).freeze_cols || '" '
 || 'ySplit="' || workbook.sheets( s ).freeze_rows || '" '
 || 'topLeftCell="' || alfan_col( workbook.sheets( s ).freeze_cols + 1 ) || ( workbook.sheets( s ).freeze_rows + 1 ) || '" '
 || 'activePane="bottomLeft" state="frozen"/>'
 );
 else
 if workbook.sheets( s ).freeze_rows > 0
 then
 t_xxx := t_xxx || '<pane ySplit="' || workbook.sheets( s ).freeze_rows || '" topLeftCell="A' || ( workbook.sheets( s ).freeze_rows + 1 ) || '" activePane="bottomLeft" state="frozen"/>';
 end if;
 if workbook.sheets( s ).freeze_cols > 0
 then
 t_xxx := t_xxx || '<pane xSplit="' || workbook.sheets( s ).freeze_cols || '" topLeftCell="' || alfan_col( workbook.sheets( s ).freeze_cols + 1 ) || '1" activePane="bottomLeft" state="frozen"/>';
 end if;
 end if;
 t_xxx := t_xxx || '</sheetView>
 </sheetViews>
 <sheetFormatPr defaultRowHeight="15" x14ac:dyDescent="0.25"/>';
 if workbook.sheets( s ).widths.count() > 0
 then
 t_xxx := t_xxx || '<cols>';
 t_col_ind := workbook.sheets( s ).widths.first();
 while t_col_ind is not null
 loop
 t_xxx := t_xxx ||
 '<col min="' || t_col_ind || '" max="' || t_col_ind || '" width="' || to_char( workbook.sheets( s ).widths( t_col_ind ), 'TM9', 'NLS_NUMERIC_CHARACTERS=.,' ) || '" customWidth="1"/>';
 t_col_ind := workbook.sheets( s ).widths.next( t_col_ind );
 end loop;
 t_xxx := t_xxx || '</cols>';
 end if;
 t_xxx := t_xxx || '<sheetData>';
 t_row_ind := workbook.sheets( s ).rows.first();
 t_tmp := null;
 while t_row_ind is not null
 loop
 t_tmp := t_tmp || '<row r="' || t_row_ind || '" spans="' || t_col_min || ':' || t_col_max || '">';
 t_len := length( t_tmp );
 t_col_ind := workbook.sheets( s ).rows( t_row_ind ).first();
 while t_col_ind is not null
 loop
 t_cell := '<c r="' || alfan_col( t_col_ind ) || t_row_ind || '"'
 || ' ' || workbook.sheets( s ).rows( t_row_ind )( t_col_ind ).style
 || '><v>'
 || to_char( workbook.sheets( s ).rows( t_row_ind )( t_col_ind ).value, 'TM9', 'NLS_NUMERIC_CHARACTERS=.,' )
 || '</v></c>';
 if t_len > 32000
 then
 dbms_lob.writeappend( t_xxx, t_len, t_tmp );
 t_tmp := null;
 t_len := 0;
 end if;
 t_tmp := t_tmp || t_cell;
 t_len := t_len + length( t_cell );
 t_col_ind := workbook.sheets( s ).rows( t_row_ind ).next( t_col_ind );
 end loop;
 t_tmp := t_tmp || '</row>';
 t_row_ind := workbook.sheets( s ).rows.next( t_row_ind );
 end loop;
 t_tmp := t_tmp || '</sheetData>';
 t_len := length( t_tmp );
 dbms_lob.writeappend( t_xxx, t_len, t_tmp );
 for a in 1 .. workbook.sheets( s ).autofilters.count()
 loop
 t_xxx := t_xxx || '<autoFilter ref="' ||
 alfan_col( nvl( workbook.sheets( s ).autofilters( a ).column_start, t_col_min ) ) ||
 nvl( workbook.sheets( s ).autofilters( a ).row_start, workbook.sheets( s ).rows.first() ) || ':' ||
 alfan_col( coalesce( workbook.sheets( s ).autofilters( a ).column_end, workbook.sheets( s ).autofilters( a ).column_start, t_col_max ) ) ||
 nvl( workbook.sheets( s ).autofilters( a ).row_end, workbook.sheets( s ).rows.last() ) || '"/>';
 end loop;
 if workbook.sheets( s ).mergecells.count() > 0
 then
 t_xxx := t_xxx || '<mergeCells count="' || to_char( workbook.sheets( s ).mergecells.count() ) || '">';
 for m in 1 .. workbook.sheets( s ).mergecells.count()
 loop
 t_xxx := t_xxx || '<mergeCell ref="' || workbook.sheets( s ).mergecells( m ) || '"/>';
 end loop;
 t_xxx := t_xxx || '</mergeCells>';
 end if;
 --
 if workbook.sheets( s ).validations.count() > 0
 then
 t_xxx := t_xxx || '<dataValidations count="' || to_char( workbook.sheets( s ).validations.count() ) || '">';
 for m in 1 .. workbook.sheets( s ).validations.count()
 loop
 t_xxx := t_xxx || '<dataValidation' ||
 ' type="' || workbook.sheets( s ).validations( m ).type || '"' ||
 ' errorStyle="' || workbook.sheets( s ).validations( m ).errorstyle || '"' ||
 ' allowBlank="' || case when nvl( workbook.sheets( s ).validations( m ).allowBlank, true ) then '1' else '0' end || '"' ||
 ' sqref="' || workbook.sheets( s ).validations( m ).sqref || '"';
 if workbook.sheets( s ).validations( m ).prompt is not null
 then
 t_xxx := t_xxx || ' showInputMessage="1" prompt="' || workbook.sheets( s ).validations( m ).prompt || '"';
 if workbook.sheets( s ).validations( m ).title is not null
 then
 t_xxx := t_xxx || ' promptTitle="' || workbook.sheets( s ).validations( m ).title || '"';
 end if;
 end if;
 if workbook.sheets( s ).validations( m ).showerrormessage
 then
 t_xxx := t_xxx || ' showErrorMessage="1"';
 if workbook.sheets( s ).validations( m ).error_title is not null
 then
 t_xxx := t_xxx || ' errorTitle="' || workbook.sheets( s ).validations( m ).error_title || '"';
 end if;
 if workbook.sheets( s ).validations( m ).error_txt is not null
 then
 t_xxx := t_xxx || ' error="' || workbook.sheets( s ).validations( m ).error_txt || '"';
 end if;
 end if;
 t_xxx := t_xxx || '>';
 if workbook.sheets( s ).validations( m ).formula1 is not null
 then
 t_xxx := t_xxx || '<formula1>' || workbook.sheets( s ).validations( m ).formula1 || '</formula1>';
 end if;
 if workbook.sheets( s ).validations( m ).formula2 is not null
 then
 t_xxx := t_xxx || '<formula2>' || workbook.sheets( s ).validations( m ).formula2 || '</formula2>';
 end if;
 t_xxx := t_xxx || '</dataValidation>';
 end loop;
 t_xxx := t_xxx || '</dataValidations>';
 end if;
 --
 if workbook.sheets( s ).hyperlinks.count() > 0
 then
 t_xxx := t_xxx || '<hyperlinks>';
 for h in 1 .. workbook.sheets( s ).hyperlinks.count()
 loop
 t_xxx := t_xxx || '<hyperlink ref="' || workbook.sheets( s ).hyperlinks( h ).cell || '" r:id="rId' || h || '"/>';
 end loop;
 t_xxx := t_xxx || '</hyperlinks>';
 end if;
 t_xxx := t_xxx || '<pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>';
 if workbook.sheets( s ).comments.count() > 0
 then
 t_xxx := t_xxx || '<legacyDrawing r:id="rId' || ( workbook.sheets( s ).hyperlinks.count() + 1 ) || '"/>';
 end if;
 --
 t_xxx := t_xxx || '</worksheet>';
 add1xml( t_excel, 'xl/worksheets/sheet' || s || '.xml', t_xxx );
 if workbook.sheets( s ).hyperlinks.count() > 0 or workbook.sheets( s ).comments.count() > 0
 then
 t_xxx := '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">';
 if workbook.sheets( s ).comments.count() > 0
 then
 t_xxx := t_xxx || '<Relationship Id="rId' || ( workbook.sheets( s ).hyperlinks.count() + 2 ) || '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="../comments' || s || '.xml"/>';
 t_xxx := t_xxx || '<Relationship Id="rId' || ( workbook.sheets( s ).hyperlinks.count() + 1 ) || '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing" Target="../drawings/vmlDrawing' || s || '.vml"/>';
 end if;
 for h in 1 .. workbook.sheets( s ).hyperlinks.count()
 loop
 t_xxx := t_xxx || '<Relationship Id="rId' || h || '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="' || workbook.sheets( s ).hyperlinks( h ).url || '" TargetMode="External"/>';
 end loop;
 t_xxx := t_xxx || '</Relationships>';
 add1xml( t_excel, 'xl/worksheets/_rels/sheet' || s || '.xml.rels', t_xxx );
 end if;
 --
 if workbook.sheets( s ).comments.count() > 0
 then
 declare
 cnt pls_integer;
 author_ind tp_author;
 -- t_col_ind := workbook.sheets( s ).widths.next( t_col_ind );
 begin
 authors.delete();
 for c in 1 .. workbook.sheets( s ).comments.count()
 loop
 authors( workbook.sheets( s ).comments( c ).author ) := 0;
 end loop;
 t_xxx := '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <comments xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
 <authors>';
 cnt := 0;
 author_ind := authors.first();
 while author_ind is not null or authors.next( author_ind ) is not null
 loop
 authors( author_ind ) := cnt;
 t_xxx := t_xxx || '<author>' || author_ind || '</author>';
 cnt := cnt + 1;
 author_ind := authors.next( author_ind );
 end loop;
 end;
 t_xxx := t_xxx || '</authors><commentList>';
 for c in 1 .. workbook.sheets( s ).comments.count()
 loop
 t_xxx := t_xxx || '<comment ref="' || alfan_col( workbook.sheets( s ).comments( c ).column ) ||
 to_char( workbook.sheets( s ).comments( c ).row || '" authorId="' || authors( workbook.sheets( s ).comments( c ).author ) ) || '">
 <text>';
 if workbook.sheets( s ).comments( c ).author is not null
 then
 t_xxx := t_xxx || '<r><rPr><b/><sz val="9"/><color indexed="81"/><rFont val="Tahoma"/><charset val="1"/></rPr><t xml:space="preserve">' ||
 workbook.sheets( s ).comments( c ).author || ':</t></r>';
 end if;
 t_xxx := t_xxx || '<r><rPr><sz val="9"/><color indexed="81"/><rFont val="Tahoma"/><charset val="1"/></rPr><t xml:space="preserve">' ||
 case when workbook.sheets( s ).comments( c ).author is not null then '
 ' end || workbook.sheets( s ).comments( c ).text || '</t></r></text></comment>';
 end loop;
 t_xxx := t_xxx || '</commentList></comments>';
 add1xml( t_excel, 'xl/comments' || s || '.xml', t_xxx );
 t_xxx := '<xml xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel">
 <o:shapelayout v:ext="edit"><o:idmap v:ext="edit" data="2"/></o:shapelayout>
 <v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m,l,21600r21600,l21600,xe"><v:stroke joinstyle="miter"/><v:path gradientshapeok="t" o:connecttype="rect"/></v:shapetype>';
 for c in 1 .. workbook.sheets( s ).comments.count()
 loop
 t_xxx := t_xxx || '<v:shape id="_x0000_s' || to_char( c ) || '" type="#_x0000_t202"
 style="position:absolute;margin-left:35.25pt;margin-top:3pt;z-index:' || to_char( c ) || ';visibility:hidden;" fillcolor="#ffffe1" o:insetmode="auto">
 <v:fill color2="#ffffe1"/><v:shadow on="t" color="black" obscured="t"/><v:path o:connecttype="none"/>
 <v:textbox style="mso-direction-alt:auto"><div style="text-align:left"></div></v:textbox>
 <x:ClientData ObjectType="Note"><x:MoveWithCells/><x:SizeWithCells/>';
 t_w := workbook.sheets( s ).comments( c ).width;
 t_c := 1;
 loop
 if workbook.sheets( s ).widths.exists( workbook.sheets( s ).comments( c ).column + t_c )
 then
 t_cw := 256 * workbook.sheets( s ).widths( workbook.sheets( s ).comments( c ).column + t_c );
 t_cw := trunc( ( t_cw + 18 ) / 256 * 7); -- assume default 11 point Calibri
 else
 t_cw := 64;
 end if;
 exit when t_w < t_cw;
 t_c := t_c + 1;
 t_w := t_w - t_cw;
 end loop;
 t_h := workbook.sheets( s ).comments( c ).height;
 t_xxx := t_xxx || to_char( '<x:Anchor>' || workbook.sheets( s ).comments( c ).column || ',15,' ||
 workbook.sheets( s ).comments( c ).row || ',30,' ||
 ( workbook.sheets( s ).comments( c ).column + t_c - 1 ) || ',' || round( t_w ) || ',' ||
 ( workbook.sheets( s ).comments( c ).row + 1 + trunc( t_h / 20 ) ) || ',' || mod( t_h, 20 ) || '</x:Anchor>' );
 t_xxx := t_xxx || to_char( '<x:AutoFill>False</x:AutoFill><x:Row>' ||
 ( workbook.sheets( s ).comments( c ).row - 1 ) || '</x:Row><x:Column>' ||
 ( workbook.sheets( s ).comments( c ).column - 1 ) || '</x:Column></x:ClientData></v:shape>' );
 end loop;
 t_xxx := t_xxx || '</xml>';
 add1xml( t_excel, 'xl/drawings/vmlDrawing' || s || '.vml', t_xxx );
 end if;
 --
 end loop;
 t_xxx := '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
 <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>
 <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
 <Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="theme/theme1.xml"/>';
 for s in 1 .. workbook.sheets.count()
 loop
 t_xxx := t_xxx || '
 <Relationship Id="rId' || ( 9 + s ) || '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet' || s || '.xml"/>';
 end loop;
 t_xxx := t_xxx || '</Relationships>';
 add1xml( t_excel, 'xl/_rels/workbook.xml.rels', t_xxx );
 t_xxx := '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="' || workbook.str_cnt || '" uniqueCount="' || workbook.strings.count() || '">';
 t_tmp := null;
 for i in 0 .. workbook.str_ind.count() - 1
 loop
 t_str := '<si><t>' || dbms_xmlgen.convert( substr( workbook.str_ind( i ), 1, 32000 ) ) || '</t></si>';
 if length( t_tmp ) + length( t_str ) > 32000
 then
 t_xxx := t_xxx || t_tmp;
 t_tmp := null;
 end if;
 t_tmp := t_tmp || t_str;
 end loop;
 t_xxx := t_xxx || t_tmp || '</sst>';
 add1xml( t_excel, 'xl/sharedStrings.xml', t_xxx );
 finish_zip( t_excel );
 clear_workbook;
 return t_excel;
 end;
 --
 procedure save
 ( p_directory varchar2
 , p_filename varchar2
 )
 is
 begin
 blob2file( finish, p_directory, p_filename );
 end;
 --
 procedure query2sheet
 ( p_sql varchar2
 , p_column_headers boolean := true
 , p_directory varchar2 := null
 , p_filename varchar2 := null
 , p_sheet pls_integer := null
 )
 is
 t_sheet pls_integer;
 t_c integer;
 t_col_cnt integer;
 t_desc_tab dbms_sql.desc_tab2;
 d_tab dbms_sql.date_table;
 n_tab dbms_sql.number_table;
 v_tab dbms_sql.varchar2_table;
 t_bulk_size pls_integer := 200;
 t_r integer;
 t_cur_row pls_integer;
 begin
 if p_sheet is null
 then
 new_sheet;
 end if;
 t_c := dbms_sql.open_cursor;
 dbms_sql.parse( t_c, p_sql, dbms_sql.native );
 dbms_sql.describe_columns2( t_c, t_col_cnt, t_desc_tab );
 for c in 1 .. t_col_cnt
 loop
 if p_column_headers
 then
 cell( c, 1, t_desc_tab( c ).col_name, p_sheet => t_sheet );
 end if;
 -- dbms_output.put_line( t_desc_tab( c ).col_name || ' ' || t_desc_tab( c ).col_type );
 case
 when t_desc_tab( c ).col_type in ( 2, 100, 101 )
 then
 dbms_sql.define_array( t_c, c, n_tab, t_bulk_size, 1 );
 when t_desc_tab( c ).col_type in ( 12, 178, 179, 180, 181 , 231 )
 then
 dbms_sql.define_array( t_c, c, d_tab, t_bulk_size, 1 );
 when t_desc_tab( c ).col_type in ( 1, 8, 9, 96, 112 )
 then
 dbms_sql.define_array( t_c, c, v_tab, t_bulk_size, 1 );
 else
 null;
 end case;
 end loop;
 --
 t_cur_row := case when p_column_headers then 2 else 1 end;
 t_sheet := nvl( p_sheet, workbook.sheets.count() );
 --
 t_r := dbms_sql.execute( t_c );
 loop
 t_r := dbms_sql.fetch_rows( t_c );
 if t_r > 0
 then
 for c in 1 .. t_col_cnt
 loop
 case
 when t_desc_tab( c ).col_type in ( 2, 100, 101 )
 then
 dbms_sql.column_value( t_c, c, n_tab );
 for i in 0 .. t_r - 1
 loop
 if n_tab( i + n_tab.first() ) is not null
 then
 cell( c, t_cur_row + i, n_tab( i + n_tab.first() ), p_sheet => t_sheet );
 end if;
 end loop;
 n_tab.delete;
 when t_desc_tab( c ).col_type in ( 12, 178, 179, 180, 181 , 231 )
 then
 dbms_sql.column_value( t_c, c, d_tab );
 for i in 0 .. t_r - 1
 loop
 if d_tab( i + d_tab.first() ) is not null
 then
 cell( c, t_cur_row + i, d_tab( i + d_tab.first() ), p_sheet => t_sheet );
 end if;
 end loop;
 d_tab.delete;
 when t_desc_tab( c ).col_type in ( 1, 8, 9, 96, 112 )
 then
 dbms_sql.column_value( t_c, c, v_tab );
 for i in 0 .. t_r - 1
 loop
 if v_tab( i + v_tab.first() ) is not null
 then
 cell( c, t_cur_row + i, v_tab( i + v_tab.first() ), p_sheet => t_sheet );
 end if;
 end loop;
 v_tab.delete;
 else
 null;
 end case;
 end loop;
 end if;
 exit when t_r != t_bulk_size;
 t_cur_row := t_cur_row + t_r;
 end loop;
 dbms_sql.close_cursor( t_c );
 if ( p_directory is not null and p_filename is not null )
 then
 save( p_directory, p_filename );
 end if;
 exception
 when others
 then
 if dbms_sql.is_open( t_c )
 then
 dbms_sql.close_cursor( t_c );
 end if;
 end;
 end;
 /
 -------------- Generate Excel Files (Run generate_excel.sql) -------------------

-- Directory name is case sensitive in below code --

begin
 as_xlsx.query2sheet( 'select * from dual' );
 as_xlsx.save( 'MY_DIR', 'my.xlsx' );
 end;
 /
 begin
 as_xlsx.query2sheet( 'select * from swx.log_record where tran_datetime > sysdate - 14' );
 as_xlsx.save( 'MY_DIR', 'test_output.xlsx' );
 end;
 /

2. Generate PDF by first creating a procedure as_pdf3 (code is in a3_pdf.sql)

————– Generate PDF Files (Run generate_pdf.sql) ——————-

— Directory name is case sensitive ib below code–

 declare
 t_rc sys_refcursor;
 t_query varchar2(1000);
 begin
 as_pdf3.init;
 as_pdf3.set_page_proc( q'~
 begin
 as_pdf3.set_font( 'helvetica', 8 );
 as_pdf3.put_txt( 10, 15, 'Page #PAGE_NR# of "PAGE_COUNT#' );
 as_pdf3.set_font( 'helvetica', 12 );
 as_pdf3.put_txt( 350, 15, 'This is a footer text' );
 as_pdf3.set_font( 'helvetica', 'B', 15 );
 as_pdf3.put_txt( 200, 780, 'This is a header text' );
 end;~' );
 as_pdf3.set_page_proc( q'~
 begin
 as_pdf3.set_font( 'Colonna MT', 'N', 50 );
 as_pdf3.put_txt( 150, 200, 'Watermark Watermark Watermark', 60 );
 end;~' );
 t_query := 'select rownum, sysdate + level, ''example'' || level from dual connect by level <= 50';
 as_pdf3.query2table( t_query );
 open t_rc for t_query;
 as_pdf3.refcursor2table( t_rc );
 as_pdf3.save_pdf('MY_DIR','my.pdf');
 end;
 /
 declare
 t_rc sys_refcursor;
 t_query varchar2(1000);
 begin
 as_pdf3.init;
 as_pdf3.set_page_proc( q'~
 begin
 as_pdf3.set_font( 'helvetica', 8 );
 as_pdf3.put_txt( 10, 15, 'Page #PAGE_NR# of "PAGE_COUNT#' );
 as_pdf3.set_font( 'helvetica', 12 );
 as_pdf3.put_txt( 350, 15, 'This is a footer text' );
 as_pdf3.set_font( 'helvetica', 'B', 15 );
 as_pdf3.put_txt( 200, 780, 'This is a header text' );
 end;~' );
 as_pdf3.set_page_proc( q'~
 begin
 as_pdf3.set_font( 'Colonna MT', 'N', 50 );
 as_pdf3.put_txt( 150, 200, 'Watermark Watermark Watermark', 60 );
 end;~' );
 t_query := 'select cardholder,card_status from swx.cardholder';
 as_pdf3.query2table( t_query );
 open t_rc for t_query;
 as_pdf3.refcursor2table( t_rc );
 as_pdf3.save_pdf('MY_DIR','my.pdf');
 end;
 /

— Above is working Sample, below is Template —


declare
 t_rc sys_refcursor;
 t_query varchar2(1000);
 begin
 as_pdf3.init;
 as_pdf3.load_ttf_font( 'MY_FONTS', 'COLONNA.TTF', 'CID' );
 as_pdf3.set_page_proc( q'~
 begin
 as_pdf3.set_font( 'helvetica', 8 );
 as_pdf3.put_txt( 10, 15, 'Page #PAGE_NR# of "PAGE_COUNT#' );
 as_pdf3.set_font( 'helvetica', 12 );
 as_pdf3.put_txt( 350, 15, 'This is a footer text' );
 as_pdf3.set_font( 'helvetica', 'B', 15 );
 as_pdf3.put_txt( 200, 780, 'This is a header text' );
 as_pdf3.put_image( 'MY_DIR', 'logo.jpg', 500, 15 );
 end;~' );
 as_pdf3.set_page_proc( q'~
 begin
 as_pdf3.set_font( 'Colonna MT', 'N', 50 );
 as_pdf3.put_txt( 150, 200, 'Watermark Watermark Watermark', 60 );
 end;~' );
 t_query := 'select rownum, sysdate + level, ''example'' || level from dual connect by level <= 50';
 as_pdf3.query2table( t_query );
 open t_rc for t_query;
 as_pdf3.refcursor2table( t_rc );
 as_pdf3.save_pdf('MY_DIR','my.pdf');
 end;
 /

— This is the PL SQL Package as_pdf3 to generate the pdf’s —

Can be downloaded here:

https://technology.amis.nl/wp-content/uploads/2012/04/as_pdf3_4.txt


CREATE OR REPLACE package as_pdf3
 is
 /**********************************************
 **
 ** Author: Anton Scheffer
 ** Date: 11-04-2012
 ** Website: http://technology.amis.nl
 ** See also: http://technology.amis.nl/?p=17718
 **
 ** Changelog:
 ** Date: 13-08-2012
 ** added two procedure for Andreas Weiden
 ** see https://sourceforge.net/projects/pljrxml2pdf/
 ** Date: 16-04-2012
 ** changed code for parse_png
 ** Date: 15-04-2012
 ** only dbms_lob.freetemporary for temporary blobs
 ** Date: 11-04-2012
 ** Initial release of as_pdf3
 **
 ******************************************************************************
 ******************************************************************************
 Copyright (C) 2012 by Anton Scheffer

Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.

******************************************************************************
 ******************************************** */
 --
 c_get_page_width constant pls_integer := 0;
 c_get_page_height constant pls_integer := 1;
 c_get_margin_top constant pls_integer := 2;
 c_get_margin_right constant pls_integer := 3;
 c_get_margin_bottom constant pls_integer := 4;
 c_get_margin_left constant pls_integer := 5;
 c_get_x constant pls_integer := 6;
 c_get_y constant pls_integer := 7;
 c_get_fontsize constant pls_integer := 8;
 c_get_current_font constant pls_integer := 9;
 --
 function file2blob( p_dir varchar2, p_file_name varchar2 )
 return blob;
 --
 function conv2uu( p_value number, p_unit varchar2 )
 return number;
 --
 procedure set_page_size
 ( p_width number
 , p_height number
 , p_unit varchar2 := 'cm'
 );
 --
 procedure set_page_format( p_format varchar2 := 'A4' );
 --
 procedure set_page_orientation( p_orientation varchar2 := 'PORTRAIT' );
 --
 procedure set_margins
 ( p_top number := null
 , p_left number := null
 , p_bottom number := null
 , p_right number := null
 , p_unit varchar2 := 'cm'
 );
 --
 procedure set_info
 ( p_title varchar2 := null
 , p_author varchar2 := null
 , p_subject varchar2 := null
 , p_keywords varchar2 := null
 );
 --
 procedure init;
 --
 function get_pdf
 return blob;
 --
 procedure save_pdf
 ( p_dir varchar2 := 'MY_DIR'
 , p_filename varchar2 := 'my.pdf'
 , p_freeblob boolean := true
 );
 --
 procedure txt2page( p_txt varchar2 );
 --
 procedure put_txt( p_x number, p_y number, p_txt varchar2, p_degrees_rotation number := null );
 --
 function str_len( p_txt varchar2 )
 return number;
 --
 procedure write
 ( p_txt in varchar2
 , p_x in number := null
 , p_y in number := null
 , p_line_height in number := null
 , p_start in number := null -- left side of the available text box
 , p_width in number := null -- width of the available text box
 , p_alignment in varchar2 := null
 );
 --
 procedure set_font
 ( p_index pls_integer
 , p_fontsize_pt number
 , p_output_to_doc boolean := true
 );
 --
 function set_font
 ( p_fontname varchar2
 , p_fontsize_pt number
 , p_output_to_doc boolean := true
 )
 return pls_integer;
 --
 procedure set_font
 ( p_fontname varchar2
 , p_fontsize_pt number
 , p_output_to_doc boolean := true
 );
 --
 function set_font
 ( p_family varchar2
 , p_style varchar2 := 'N'
 , p_fontsize_pt number := null
 , p_output_to_doc boolean := true
 )
 return pls_integer;
 --
 procedure set_font
 ( p_family varchar2
 , p_style varchar2 := 'N'
 , p_fontsize_pt number := null
 , p_output_to_doc boolean := true
 );
 --
 procedure new_page;
 --
 function load_ttf_font
 ( p_font blob
 , p_encoding varchar2 := 'WINDOWS-1252'
 , p_embed boolean := false
 , p_compress boolean := true
 , p_offset number := 1
 )
 return pls_integer;
 --
 procedure load_ttf_font
 ( p_font blob
 , p_encoding varchar2 := 'WINDOWS-1252'
 , p_embed boolean := false
 , p_compress boolean := true
 , p_offset number := 1
 );
 --
 function load_ttf_font
 ( p_dir varchar2 := 'MY_FONTS'
 , p_filename varchar2 := 'BAUHS93.TTF'
 , p_encoding varchar2 := 'WINDOWS-1252'
 , p_embed boolean := false
 , p_compress boolean := true
 )
 return pls_integer;
 --
 procedure load_ttf_font
 ( p_dir varchar2 := 'MY_FONTS'
 , p_filename varchar2 := 'BAUHS93.TTF'
 , p_encoding varchar2 := 'WINDOWS-1252'
 , p_embed boolean := false
 , p_compress boolean := true
 );
 --
 procedure load_ttc_fonts
 ( p_ttc blob
 , p_encoding varchar2 := 'WINDOWS-1252'
 , p_embed boolean := false
 , p_compress boolean := true
 );
 --
 procedure load_ttc_fonts
 ( p_dir varchar2 := 'MY_FONTS'
 , p_filename varchar2 := 'CAMBRIA.TTC'
 , p_encoding varchar2 := 'WINDOWS-1252'
 , p_embed boolean := false
 , p_compress boolean := true
 );
 --
 procedure set_color( p_rgb varchar2 := '000000' );
 --
 procedure set_color
 ( p_red number := 0
 , p_green number := 0
 , p_blue number := 0
 );
 --
 procedure set_bk_color( p_rgb varchar2 := 'ffffff' );
 --
 procedure set_bk_color
 ( p_red number := 0
 , p_green number := 0
 , p_blue number := 0
 );
 --
 procedure horizontal_line
 ( p_x in number
 , p_y in number
 , p_width in number
 , p_line_width in number := 0.5
 , p_line_color in varchar2 := '000000'
 );
 --
 procedure vertical_line
 ( p_x in number
 , p_y in number
 , p_height in number
 , p_line_width in number := 0.5
 , p_line_color in varchar2 := '000000'
 );
 --
 procedure rect
 ( p_x in number
 , p_y in number
 , p_width in number
 , p_height in number
 , p_line_color in varchar2 := null
 , p_fill_color in varchar2 := null
 , p_line_width in number := 0.5
 );
 --
 function get( p_what in pls_integer )
 return number;
 --
 procedure put_image
 ( p_img blob
 , p_x number
 , p_y number
 , p_width number := null
 , p_height number := null
 , p_align varchar2 := 'center'
 , p_valign varchar2 := 'top'
 );
 --
 procedure put_image
 ( p_dir varchar2
 , p_file_name varchar2
 , p_x number
 , p_y number
 , p_width number := null
 , p_height number := null
 , p_align varchar2 := 'center'
 , p_valign varchar2 := 'top'
 );
 --
 procedure put_image
 ( p_url varchar2
 , p_x number
 , p_y number
 , p_width number := null
 , p_height number := null
 , p_align varchar2 := 'center'
 , p_valign varchar2 := 'top'
 );
 --
 procedure set_page_proc( p_src clob );
 --
 type tp_col_widths is table of number;
 type tp_headers is table of varchar2(32767);
 --
 procedure query2table
 ( p_query varchar2
 , p_widths tp_col_widths := null
 , p_headers tp_headers := null
 );
 --
 $IF not DBMS_DB_VERSION.VER_LE_10 $THEN
 procedure refcursor2table
 ( p_rc sys_refcursor
 , p_widths tp_col_widths := null
 , p_headers tp_headers := null
 );
 --
 $END
 --
 procedure pr_goto_page( i_npage number );
 --
 procedure pr_goto_current_page;
 /*
 begin
 as_pdf3.init;
 as_pdf3.write( 'Minimal usage' );
 as_pdf3.save_pdf;
 end;
 --
 begin
 as_pdf3.init;
 as_pdf3.write( 'Some text with a newline-character included at this "
 " place.' );
 as_pdf3.write( 'Normally text written with as_pdf3.write() is appended after the previous text. But the text wraps automaticly to a new line.' );
 as_pdf3.write( 'But you can place your text at any place', -1, 700 );
 as_pdf3.write( 'you want', 100, 650 );
 as_pdf3.write( 'You can even align it, left, right, or centered', p_y => 600, p_alignment => 'right' );
 as_pdf3.save_pdf;
 end;
 --
 begin
 as_pdf3.init;
 as_pdf3.write( 'The 14 standard PDF-fonts and the WINDOWS-1252 encoding.' );
 as_pdf3.set_font( 'helvetica' );
 as_pdf3.write( 'helvetica, normal: ' || 'The quick brown fox jumps over the lazy dog. 1234567890', -1, 700 );
 as_pdf3.set_font( 'helvetica', 'I' );
 as_pdf3.write( 'helvetica, italic: ' || 'The quick brown fox jumps over the lazy dog. 1234567890', -1, -1 );
 as_pdf3.set_font( 'helvetica', 'b' );
 as_pdf3.write( 'helvetica, bold: ' || 'The quick brown fox jumps over the lazy dog. 1234567890', -1, -1 );
 as_pdf3.set_font( 'helvetica', 'BI' );
 as_pdf3.write( 'helvetica, bold italic: ' || 'The quick brown fox jumps over the lazy dog. 1234567890', -1, -1 );
 as_pdf3.set_font( 'times' );
 as_pdf3.write( 'times, normal: ' || 'The quick brown fox jumps over the lazy dog. 1234567890', -1, 625 );
 as_pdf3.set_font( 'times', 'I' );
 as_pdf3.write( 'times, italic: ' || 'The quick brown fox jumps over the lazy dog. 1234567890', -1, -1 );
 as_pdf3.set_font( 'times', 'b' );
 as_pdf3.write( 'times, bold: ' || 'The quick brown fox jumps over the lazy dog. 1234567890', -1, -1 );
 as_pdf3.set_font( 'times', 'BI' );
 as_pdf3.write( 'times, bold italic: ' || 'The quick brown fox jumps over the lazy dog. 1234567890', -1, -1 );
 as_pdf3.set_font( 'courier' );
 as_pdf3.write( 'courier, normal: ' || 'The quick brown fox jumps over the lazy dog. 1234567890', -1, 550 );
 as_pdf3.set_font( 'courier', 'I' );
 as_pdf3.write( 'courier, italic: ' || 'The quick brown fox jumps over the lazy dog. 1234567890', -1, -1 );
 as_pdf3.set_font( 'courier', 'b' );
 as_pdf3.write( 'courier, bold: ' || 'The quick brown fox jumps over the lazy dog. 1234567890', -1, -1 );
 as_pdf3.set_font( 'courier', 'BI' );
 as_pdf3.write( 'courier, bold italic: ' || 'The quick brown fox jumps over the lazy dog. 1234567890', -1, -1 );
 --
 as_pdf3.set_font( 'courier' );
 as_pdf3.write( 'symbol:', -1, 475 );
 as_pdf3.set_font( 'symbol' );
 as_pdf3.write( 'The quick brown fox jumps over the lazy dog. 1234567890', -1, -1 );
 as_pdf3.set_font( 'courier' );
 as_pdf3.write( 'zapfdingbats:', -1, -1 );
 as_pdf3.set_font( 'zapfdingbats' );
 as_pdf3.write( 'The quick brown fox jumps over the lazy dog. 1234567890', -1, -1 );
 --
 as_pdf3.set_font( 'times', 'N', 20 );
 as_pdf3.write( 'times, normal with fontsize 20pt', -1, 400 );
 as_pdf3.set_font( 'times', 'N', 6 );
 as_pdf3.write( 'times, normal with fontsize 5pt', -1, -1 );
 as_pdf3.save_pdf;
 end;
 --
 declare
 x pls_integer;
 begin
 as_pdf3.init;
 as_pdf3.write( 'But others fonts and encodings are possible using TrueType fontfiles.' );
 x := as_pdf3.load_ttf_font( 'MY_FONTS', 'refsan.ttf', 'CID', p_compress => false );
 as_pdf3.set_font( x, 12 );
 as_pdf3.write( 'The Windows MSReference SansSerif font contains a lot of encodings, for instance', -1, 700 );
 as_pdf3.set_font( x, 15 );
 as_pdf3.write( 'Albanian: Kush mund të lexoni këtë diçka si kjo', -1, -1 );
 as_pdf3.write( 'Croatic: Tko može citati to nešto poput ovoga', -1, -1 );
 as_pdf3.write( 'Russian: ??? ????? ????????? ??? ???-?? ????? ?????', -1, -1);
 as_pdf3.write( 'Greek: ????? µp??e? ?a d?aß?se? a?t? t? ??t? sa? a?t?', -1, -1 );
 --
 as_pdf3.set_font( 'helvetica', 12 );
 as_pdf3.write( 'Or by using a TrueType collection file (ttc).', -1, 600 );
 as_pdf3.load_ttc_fonts( 'MY_FONTS', 'cambria.ttc', p_embed => true, p_compress => false );
 as_pdf3.set_font( 'cambria', 15 ); -- font family
 as_pdf3.write( 'Anton, testing 1,2,3 with Cambria', -1, -1 );
 as_pdf3.set_font( 'CambriaMT', 15 ); -- fontname
 as_pdf3.write( 'Anton, testing 1,2,3 with CambriaMath', -1, -1 );
 as_pdf3.save_pdf;
 end;
 --
 begin
 as_pdf3.init;
 for i in 1 .. 10
 loop
 as_pdf3.horizontal_line( 30, 700 - i * 15, 100, i );
 end loop;
 for i in 1 .. 10
 loop
 as_pdf3.vertical_line( 150 + i * 15, 700, 100, i );
 end loop;
 for i in 0 .. 255
 loop
 as_pdf3.horizontal_line( 330, 700 - i, 100, 2, p_line_color => to_char( i, 'fm0x' ) || to_char( i, 'fm0x' ) || to_char( i, 'fm0x' ) );
 end loop;
 as_pdf3.save_pdf;
 end;
 --
 declare
 t_logo varchar2(32767) :=
 '/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkS' ||
 'Ew8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJ' ||
 'CQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy' ||
 'MjIyMjIyMjIyMjIyMjL/wAARCABqAJYDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEA' ||
 'AAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIh' ||
 'MUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6' ||
 'Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZ' ||
 'mqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx' ||
 '8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREA' ||
 'AgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAV' ||
 'YnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hp' ||
 'anN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPE' ||
 'xcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD3' ||
 '+iiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAoorifiX4pk' ||
 '8PaCILR9t9eExxsOqL/E315AHuaUmkrs1oUZVqipw3ZU8X/FCz0KeSw02Jb2+Thy' ||
 'WxHGfQkdT7D8686ufih4suGJW/jgXssUC8fnk1ydvbz3lzHb28bzTyttRF5LMa7H' ||
 'Uvh+3hvRI9T1+7kUPIsf2ezUMykgnlmIHbtXI5znqtj66ng8DhFGFRJyffVv5Fnw' ||
 'r8QfEEvinTodR1N5rSaYRyIyIAd3A5A9SK7X4qeINV0Gz019LvGtmlkcOVVTkADH' ||
 'UGvNdDsPDepa7ZWdtPrMU8syiN3EWFbqCcfSu3+NXGnaOM5/ev8A+giqi5ezepy1' ||
 '6NF4+koxsne6scronxO1+01i2l1K/e6st2Joyij5T1IwByOv4V75BPHc28c8Lh45' ||
 'FDKynIIPINfJleheGPiPJong+802Ul7uEYsCRkYbsfZev04pUqttJF5rlSqKM6Eb' ||
 'PZpGv8RfiFf2etDTNDu/I+zf8fEqqG3Of4eQen8z7VB8O/GGv6x4vhs9Q1J57don' ||
 'YoUUZIHHQV5fI7yyNJIxd3JZmY5JJ6k12nwo/wCR8t/+uEn8qUajlM6K+Ao0MFJc' ||
 'qbS363O1+KviTWNBuNMXS71rYTLIZAqqd2NuOoPqayvht4u17WvFf2TUdRe4g+zu' ||
 '+woo5BXB4HuaX42f8fOj/wC7L/Naw/hH/wAjv/26yfzWqcn7W1zjpUKTytzcVez1' ||
 'sdt8QviJN4euhpelJG16VDSyuMiIHoMdz3rzZviN4tZif7YkHsIkx/6DTPiAkqeO' ||
 '9WE2dxlBXP8Ad2jH6VJ4H8LWfizUp7S51FrV40DoiKC0nPOM+nH51MpTlOyOvDYX' ||
 'C4fCKrUinpdu1zovAfjvXL7xfZ2ep6i89tOGTayKPmxkHgD0/WvbK83074RWWman' ||
 'a30Wr3Zkt5VlUFVwSDnHSvQZ7u2tU3XE8cSju7gD9a6Kakl7x89mVTD1aqlh1pbt' ||
 'YnorDfxj4eWTy11W3lfpthbzD+S5q7ZavBfy7IIrrGM75Ld41/NgKu6OB05pXaL9' ||
 'FFFMgK8A+K+ote+NZYM5jtIliA9yNx/mPyr37tXzP42cv421gseftLD8sCsK7909' ||
 'zIIKWJcn0Rf8Aa5o3h3WJtR1VZmdY9kAjj3YJ+8fbjj8TW/8QPHuj+J/D6WNgLjz' ||
 'lnWQ+ZHtGAD3z71wNno2qahEZbLTrq5jB2l4oiwB9Mii80XVNPhE17p11bxE7d8s' ||
 'RUZ9MmsFOSjZLQ9+phMNUxKqyl7y6XNHwR/yO+j/APXyP5GvQ/jX/wAg/SP+ur/+' ||
 'givPPBH/ACO+j/8AXyP5GvQ/jX/yD9I/66v/AOgirh/CZyYv/kZ0vT/M8y8PaM/i' ||
 'DV106J9kskcjRk9NyqSAfY4xWbLFJBM8UqFJI2KurDBUjgg11nww/wCR/sP92T/0' ||
 'A16B4p+Gq614xtNQg2pZznN+AcH5e4/3uh/OojT5o3R0V8xjh8S6dT4bX+ev5nk1' ||
 '7oU+n+HtP1W4yv26RxEhH8CgfN+JP5V0Hwo/5Hy3/wCuEn8q6b4zxJBY6JFEgSNG' ||
 'kVVUYAAC4Fcn8MbqG08bQyzyBEEMnJ78dB6mq5VGokZ+3licunUe7TOn+Nn/AB86' ||
 'P/uy/wA1rD+EZA8bEk4AtJMn8Vru/GHhW58c3lhKrmws7ZX3yzp875x91e3Tvj6V' ||
 'zduPDPh6/GneGtOl8Qa2wKmRnzGvrk/dx9B+NXKL9pzHDQxEHgPq8dZWd/L1exf+' ||
 'JHhuPxFdw6hozLPeIPLnCnCbBkhi5+UEfXofauEtLWy8OX0N7L4hQ3sDBli01POI' ||
 'PoXOF9j1r1O18E6nrhSfxbqJkjHK6baHy4E9jjlq84+IXg4+GNWE1qh/sy5JMX/T' ||
 'Nu6f1Ht9KVSL+OxeXYiMrYSU/wCu13/l8zudCn1jx3avcxaybO1Vijorbph9Qu1V' ||
 'z/wKt+y+HHh63fzrq3k1CfqZbyQyc/Tp+leL+CvE0vhjxDDc7z9klIjuU7FSev1H' ||
 'X8/WvpNWDqGUggjIIrSk1NXe5wZpTq4Spywdova2hFbWVrZxiO2t4oUH8MaBR+lT' ||
 '0UVseM23uFFFFAgr5y+I9obPx5qQIwsrLKvuCo/qDX0bXkPxn0YiSw1mNflINvKf' ||
 'Tuv/ALNWNdXiexklZU8Uk/tKxb+C16j6bqVgSN8cyygezDH81rR+MQ/4o6L/AK+0' ||
 '/k1cV8JrXVv+Em+2WkJNgEaO5kY4XHUAerZxxXpHxB0b/hIdBSxjv7W1kWdZC1w2' ||
 'BgA/40oXdOxti1CjmanfS6b8jxbwR/yO+j/9fI/ka9D+Nf8AyD9I/wCur/8AoIrG' ||
 '8PeCJtJ8RWOoHVLa7S2lDslpFJIT7AgY/Ouu8a+HNT8bx2EVvB9hit3ZmkuiMkEY' ||
 '4VST+eKiMGqbR1YnFUZY+nWT91L/ADPN/hh/yP8AYf7sn/oBr3y51O1tHEbybpj0' ||
 'ijBZz/wEc1xXh34WafoVyl7PqNzNcoD8yN5SgEYPTn9auar438K+FI3hhkjluB1h' ||
 'tQGYn/abp+ZzWlNckfeOHMakcbiL0E5aW2F8SeFJPG01kb7fYWlqWYKCDLJnHXsv' ||
 'T3/Cqdzqngz4cwGC0hje+xjyofnmY/7THp+P5VjHUvHfjxWXToBoult/y1clWcfX' ||
 'GT+AH1qx4Q+GN/oXiSLUtQurO5iRW+UKxbceh5HX3ovd3ivmChGnT5MRU0X2U/zZ' ||
 'yfjXxR4p1K2ga/gfTNOu9xhtlOGdRjl+56j0HtS/CL/kd/8At1k/mteg/EHwRfeL' ||
 'ZbB7O5t4RbhwwlB53Y6Y+lZ/gf4c6l4Y8Q/2jdXlrLH5LR7Yw2ckj1+lRyS9pc7F' ||
 'jsM8BKmrRk09EQeNviHrnhnxLLp8FtZvBsWSNpFbcQRznB9Qa4bxF8Q9Y8S6abC8' ||
 'htI4CwY+Wh3ZByOSTivS/H/gC78V6haXllcwQPHGY5PNB+YZyMY+prkP+FMa3/0E' ||
 'rH8n/wAKKiqNtLYeBrZdCnCc7Ka9TzcKzkKoJZuAB3NfVWjwS22i2UE3MscCI/1C' ||
 'gGuE8LfCe20e/i1DU7sXk8Lbo40TbGrdic8nFekVVGm46s485x9PEyjGlql1Ciii' ||
 'tzxAooooAKo6vpFnrmmS6ffRl7eXG4A4PByCD26VeooHGTi7rcxL3w9btpEen2Nr' ||
 'aRxRDEcciHaP++SDXG3fhzxxZzCTSpNICDpGqE5/77BP616bRUuKZ0UsVOn5+up5' ||
 'd/wkfxI0vi98Nw3ajq0A5/8AHWP8qgfxz461aQwaX4Za2boWljY7T9W2ivWKTA9K' ||
 'nkfc3WNpbujG/wA/yPKl8DeM/EZ3eI/EDW8DdYITn8MDC/zrqtC+HXh3QiskdmLi' ||
 '4XkTXHzkH2HQfgK6yimoJamdTH1prlTsuy0QgAHAGKWsvWHvVNsLcS+QXIuGhAMg' ||
 'G04wD74z3rHmfxAxkEJuFk3SL8yIUEe07GHq+duR67uMYqm7GEaXNrdHWUVx7z+K' ||
 'y+/yiCixnylC4coX389t+Fx6ZHvTbj/hKHjufmmV1ineLywmN+UMa89cAsPfFLmL' ||
 '+r/3l952VFcpqdvrcEt0bO4vJI1SAx/dOSZCJO2eFxSwPrZ1IBTc+WJ4wBIoEZh2' ||
 'DeScZ3bt2O+cdqLi9j7t+ZHVUVzFzHrUN/dNFLdPaiaMADaSIyMuUGOSDgfTOKWV' ||
 '/ES6XCbcF7j7S4XzAoJi2vs39hzt6e3vTuL2O2qOmormjHqU32F4ptRUGbFysgQE' ||
 'LsY+n97aOK6KJzJEjlGTcoO1uo9j70XIlDl6j6KKKZAUUUUAFFFFABRRRQAUUUUA' ||
 'Y3iDV59JjgNvCkrylwA5IAKxsw6e6gVnnxTchjmwZMSm2MbZ3LMUDKvoVJyN3Toa' ||
 '6ggHqAaMD0FKzNYzglZxuci3i26jghmeCAiXG9Fc7rf94qEP/wB9H05HfrUl74ou' ||
 '4PtKxW0TG3lQM+4lTG7KI2HrkMe/8JrqTGhzlF568daPLTbt2Lt6YxxSs+5ftKd/' ||
 'hOah8SXL6iLcxwSL9ojgKITvIaMMXHJGBn8h1qO48V3Vs1y5sA8EJmVnQklSrbUJ' ||
 'Hoe5HTjtXUrGinKooOMcCl2r6D8qLMXtKd/hOX1fxFqNjd3qW1ik0VpAszkkjgq5' ||
 'zn2Kjjqc0j+JrmNeIoGZIkk25wZ9zEbY8E8jHqeSOldTtU5yBz1poiRcAIox0wOl' ||
 'Fn3D2lOyXKcvZeJ72W5tPtVpFDaXErxiZmK4KiTjnr9wc+9aHh/W21W0WW4MMckh' ||
 'OyNTzx178/pWyY0ZdrIpHoRQsaISVRQT6ChJinUhJO0bDqKKKoxCiiigAooooAKK' ||
 'KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//Z';
 begin
 as_pdf3.init;
 as_pdf3.put_image( to_blob( utl_encode.base64_decode( utl_raw.cast_to_raw( t_logo ) ) )
 , 0
 , as_pdf3.get( as_pdf3.C_GET_PAGE_HEIGHT ) - 260
 , as_pdf3.get( as_pdf3.C_GET_PAGE_WIDTH )
 );
 as_pdf3.write( 'jpg, gif and png images are supported.' );
 as_pdf3.write( 'And because PDF 1.3 (thats the format I use) doesn''t support alpha channels, neither does AS_PDF.', -1, -1 );
 as_pdf3.save_pdf;
 end;
 --
 declare
 t_rc sys_refcursor;
 t_query varchar2(1000);
 begin
 as_pdf3.init;
 as_pdf3.load_ttf_font( 'MY_FONTS', 'COLONNA.TTF', 'CID' );
 as_pdf3.set_page_proc( q'~
 begin
 as_pdf3.set_font( 'helvetica', 8 );
 as_pdf3.put_txt( 10, 15, 'Page #PAGE_NR# of "PAGE_COUNT#' );
 as_pdf3.set_font( 'helvetica', 12 );
 as_pdf3.put_txt( 350, 15, 'This is a footer text' );
 as_pdf3.set_font( 'helvetica', 'B', 15 );
 as_pdf3.put_txt( 200, 780, 'This is a header text' );
 as_pdf3.put_image( 'MY_DIR', 'amis.jpg', 500, 15 );
 end;~' );
 as_pdf3.set_page_proc( q'~
 begin
 as_pdf3.set_font( 'Colonna MT', 'N', 50 );
 as_pdf3.put_txt( 150, 200, 'Watermark Watermark Watermark', 60 );
 end;~' );
 t_query := 'select rownum, sysdate + level, ''example'' || level from dual connect by level <= 50';
 as_pdf3.query2table( t_query );
 open t_rc for t_query;
 as_pdf3.refcursor2table( t_rc );
 as_pdf3.save_pdf;
 end;
 */
 end;
 /

CREATE OR REPLACE package body as_pdf3
 is
 --
 type tp_pls_tab is table of pls_integer index by pls_integer;
 type tp_objects_tab is table of number(10) index by pls_integer;
 type tp_pages_tab is table of blob index by pls_integer;
 type tp_settings is record
 ( page_width number
 , page_height number
 , margin_left number
 , margin_right number
 , margin_top number
 , margin_bottom number
 );
 type tp_font is record
 ( standard boolean
 , family varchar2(100)
 , style varchar2(2) -- N Normal
 -- I Italic
 -- B Bold
 -- BI Bold Italic
 , subtype varchar2(15)
 , name varchar2(100)
 , fontname varchar2(100)
 , char_width_tab tp_pls_tab
 , encoding varchar2(100) , charset varchar2(1000)
 , compress_font boolean := true
 , fontsize number
 , unit_norm number
 , bb_xmin pls_integer
 , bb_ymin pls_integer
 , bb_xmax pls_integer
 , bb_ymax pls_integer
 , flags pls_integer
 , first_char pls_integer
 , last_char pls_integer
 , italic_angle number
 , ascent pls_integer
 , descent pls_integer
 , capheight pls_integer
 , stemv pls_integer
 , diff varchar2(32767)
 , cid boolean := false
 , fontfile2 blob
 , ttf_offset pls_integer
 , used_chars tp_pls_tab
 , numGlyphs pls_integer
 , indexToLocFormat pls_integer
 , loca tp_pls_tab
 , code2glyph tp_pls_tab
 , hmetrics tp_pls_tab
 );
 type tp_font_tab is table of tp_font index by pls_integer;
 type tp_img is record
 ( adler32 varchar2(8)
 , width pls_integer
 , height pls_integer
 , color_res pls_integer
 , color_tab raw(768)
 , greyscale boolean
 , pixels blob
 , type varchar2(5)
 , nr_colors pls_integer
 , transparancy_index pls_integer
 );
 type tp_img_tab is table of tp_img index by pls_integer;
 type tp_info is record
 ( title varchar2(1024)
 , author varchar2(1024)
 , subject varchar2(1024)
 , keywords varchar2(32767)
 );
 type tp_page_prcs is table of clob index by pls_integer;
 --
 -- globals
 g_pdf_doc blob; -- the PDF-document being constructed
 g_objects tp_objects_tab;
 g_pages tp_pages_tab;
 g_settings tp_settings;
 g_fonts tp_font_tab;
 g_used_fonts tp_pls_tab;
 g_current_font pls_integer;
 g_images tp_img_tab;
 g_x number; -- current x-location of the "cursor"
 g_y number; -- current y-location of the "cursor"
 g_info tp_info;
 g_page_nr pls_integer;
 g_page_prcs tp_page_prcs;
 --
 -- constants
 c_nl constant varchar2(2) := chr(13) || chr(10);
 --
 function num2raw( p_value number )
 return raw
 is
 begin
 return hextoraw( to_char( p_value, 'FM0XXXXXXX' ) );
 end;
 --
 function raw2num( p_value raw )
 return number
 is
 begin
 return to_number( rawtohex( p_value ), 'XXXXXXXX' );
 end;
 --
 function raw2num( p_value raw, p_pos pls_integer, p_len pls_integer )
 return pls_integer
 is
 begin
 return to_number( rawtohex( utl_raw.substr( p_value, p_pos, p_len ) ), 'XXXXXXXX' );
 end;
 --
 function to_short( p_val raw, p_factor number := 1 )
 return number
 is
 t_rv number;
 begin
 t_rv := to_number( rawtohex( p_val ), 'XXXXXXXXXX' );
 if t_rv > 32767
 then
 t_rv := t_rv - 65536;
 end if;
 return t_rv * p_factor;
 end;
 --
 function blob2num( p_blob blob, p_len integer, p_pos integer )
 return number
 is
 begin
 return to_number( rawtohex( dbms_lob.substr( p_blob, p_len, p_pos ) ), 'xxxxxxxx' );
 end;
 --
 function file2blob( p_dir varchar2, p_file_name varchar2 )
 return blob
 is
 t_raw raw(32767);
 t_blob blob;
 fh utl_file.file_type;
 begin
 fh := utl_file.fopen( p_dir, p_file_name, 'rb' );
 dbms_lob.createtemporary( t_blob, true );
 loop
 begin
 utl_file.get_raw( fh, t_raw );
 dbms_lob.append( t_blob, t_raw );
 exception
 when no_data_found
 then
 exit;
 end;
 end loop;
 utl_file.fclose( fh );
 return t_blob;
 exception
 when others
 then
 if utl_file.is_open( fh )
 then
 utl_file.fclose( fh );
 end if;
 raise;
 end;
 --
 procedure init_core_fonts
 is
 function uncompress_withs( p_compressed_tab varchar2 )
 return tp_pls_tab
 is
 t_rv tp_pls_tab;
 t_tmp raw(32767);
 begin
 if p_compressed_tab is not null
 then
 t_tmp := utl_compress.lz_uncompress

( utl_encode.base64_decode( utl_raw.cast_to_raw( p_compressed_tab ) ) );
 for i in 0 .. 255
 loop
 t_rv( i ) := to_number( utl_raw.substr( t_tmp, i * 4 + 1, 4 ), '0xxxxxxx' );
 end loop;
 end if;
 return t_rv;
 end;
 --
 procedure init_core_font
 ( p_ind pls_integer
 , p_family varchar2
 , p_style varchar2
 , p_name varchar2
 , p_compressed_tab varchar2
 )
 is
 begin
 g_fonts( p_ind ).family := p_family;
 g_fonts( p_ind ).style := p_style;
 g_fonts( p_ind ).name := p_name;
 g_fonts( p_ind ).fontname := p_name;
 g_fonts( p_ind ).standard := true;
 g_fonts( p_ind ).encoding := 'WE8MSWIN1252';
 g_fonts( p_ind ).charset := sys_context( 'userenv', 'LANGUAGE' );
 g_fonts( p_ind ).charset := substr( g_fonts( p_ind ).charset
 , 1
 , instr( g_fonts( p_ind ).charset, '.' )
 ) || g_fonts( p_ind ).encoding;
 g_fonts( p_ind ).char_width_tab := uncompress_withs( p_compressed_tab );
 end;
 begin
 init_core_font( 1, 'helvetica', 'N', 'Helvetica'
 , 'H4sIAAAAAAAAC81Tuw3CMBC94FQMgMQOLAGVGzNCGtc0dAxAT+8lsgE7RKJFomOA'
 || 'SLT4frHjBEFJ8XSX87372C8A1Qr+Ax5gsWGYU7QBAK4x7gTnGLOS6xJPOd8w5NsM'
 || '2OvFvQidAP04j1nyN3F7iSNny3E6DylPeeqbNqvti31vMpfLZuzH86oPdwaeo6X+'
 || '5X6Oz5VHtTqJKfYRNVu6y0ZyG66rdcxzXJe+Q/KJ59kql+bTt5K6lKucXvxWeHKf'
 || '+p6Tfersfh7RHuXMZjHsdUkxBeWtM60gDjLTLoHeKsyDdu6m8VK3qhnUQAmca9BG'
 || 'Dq3nP+sV/4FcD6WOf9K/ne+hdav+DTuNLeYABAAA' );
 --
 init_core_font( 2, 'helvetica', 'I', 'Helvetica-Oblique'
 , 'H4sIAAAAAAAAC81Tuw3CMBC94FQMgMQOLAGVGzNCGtc0dAxAT+8lsgE7RKJFomOA'
 || 'SLT4frHjBEFJ8XSX87372C8A1Qr+Ax5gsWGYU7QBAK4x7gTnGLOS6xJPOd8w5NsM'
 || '2OvFvQidAP04j1nyN3F7iSNny3E6DylPeeqbNqvti31vMpfLZuzH86oPdwaeo6X+'
 || '5X6Oz5VHtTqJKfYRNVu6y0ZyG66rdcxzXJe+Q/KJ59kql+bTt5K6lKucXvxWeHKf'
 || '+p6Tfersfh7RHuXMZjHsdUkxBeWtM60gDjLTLoHeKsyDdu6m8VK3qhnUQAmca9BG'
 || 'Dq3nP+sV/4FcD6WOf9K/ne+hdav+DTuNLeYABAAA' );
 --
 init_core_font( 3, 'helvetica', 'B', 'Helvetica-Bold'
 , 'H4sIAAAAAAAAC8VSsRHCMAx0SJcBcgyRJaBKkxXSqKahYwB6+iyRTbhLSUdHRZUB'
 || 'sOWXLF8SKCn+ZL/0kizZuaJ2/0fn8XBu10SUF28n59wbvoCr51oTD61ofkHyhBwK'
 || '8rXusVaGAb4q3rXOBP4Qz+wfUpzo5FyO4MBr39IH+uLclFvmCTrz1mB5PpSD52N1'
 || 'DfqS988xptibWfbw9Sa/jytf+dz4PqQz6wi63uxxBpCXY7uUj88jNDNy1mYGdl97'
 || '856nt2f4WsOFed4SpzumNCvlT+jpmKC7WgH3PJn9DaZfA42vlgh96d+wkHy0/V95'
 || 'xyv8oj59QbvBN2I/iAuqEAAEAAA=' );
 --
 init_core_font( 4, 'helvetica', 'BI', 'Helvetica-BoldOblique'
 , 'H4sIAAAAAAAAC8VSsRHCMAx0SJcBcgyRJaBKkxXSqKahYwB6+iyRTbhLSUdHRZUB'
 || 'sOWXLF8SKCn+ZL/0kizZuaJ2/0fn8XBu10SUF28n59wbvoCr51oTD61ofkHyhBwK'
 || '8rXusVaGAb4q3rXOBP4Qz+wfUpzo5FyO4MBr39IH+uLclFvmCTrz1mB5PpSD52N1'
 || 'DfqS988xptibWfbw9Sa/jytf+dz4PqQz6wi63uxxBpCXY7uUj88jNDNy1mYGdl97'
 || '856nt2f4WsOFed4SpzumNCvlT+jpmKC7WgH3PJn9DaZfA42vlgh96d+wkHy0/V95'
 || 'xyv8oj59QbvBN2I/iAuqEAAEAAA=' );
 --
 init_core_font( 5, 'times', 'N', 'Times-Roman'
 , 'H4sIAAAAAAAAC8WSKxLCQAyG+3Bopo4bVHbwHGCvUNNT9AB4JEwvgUBimUF3wCNR'
 || 'qAoGRZL9twlQikR8kzTvZBtF0SP6O7Ej1kTnSRfEhHw7+Jy3J4XGi8w05yeZh2sE'
 || '4j312ZDeEg1gvSJy6C36L9WX1urr4xrolfrSrYmrUCeDPGMu5+cQ3Ur3OXvQ+TYf'
 || '+2FGexOZvTM1L3S3o5fJjGQJX2n68U2ur3X5m3cTvfbxsk9pcsMee60rdTjnhNkc'
 || 'Zip9HOv9+7/tI3Oif3InOdV/oLdx3gq2HIRaB1Ob7XPk35QwwxDyxg3e09Dv6nSf'
 || 'rxQjvty8ywDce9CXvdF9R+4y4o+7J1P/I9sABAAA' );
 --
 init_core_font( 6, 'times', 'I', 'Times-Italic'
 , 'H4sIAAAAAAAAC8WSPQ6CQBCFF+i01NB5g63tPcBegYZTeAB6SxNLjLUH4BTEeAYr'
 || 'Kwpj5ezsW2YgoKXFl2Hnb9+wY4x5m7+TOOJMdIFsRywodkfMBX9aSz7bXGp+gj6+'
 || 'R4TvOtJ3CU5Eq85tgGsbxG3QN8iFZY1WzpxXwkckFTR7e1G6osZGWT1bDuBnTeP5'
 || 'KtW/E71c0yB2IFbBphuyBXIL9Y/9fPvhf8se6vsa8nmeQtU6NSf6ch9fc8P9DpqK'
 || 'cPa5/I7VxDwruTN9kV3LDvQ+h1m8z4I4x9LIbnn/Fv6nwOdyGq+d33jk7/cxztyq'
 || 'XRhTz/it7Mscg7fT5CO+9ahnYk20Hww5IrwABAAA' );
 --
 init_core_font( 7, 'times', 'B', 'Times-Bold'
 , 'H4sIAAAAAAAAC8VSuw3CQAy9XBqUAVKxAZkgHQUNEiukySxpqOjTMQEDZIrUDICE'
 || 'RHUVVfy9c0IQJcWTfbafv+ece7u/Izs553cgAyN/APagl+wjgN3XKZ5kmTg/IXkw'
 || 'h4JqXUEfAb1I1VvwFYysk9iCffmN4+gtccSr5nlwDpuTepCZ/MH0FZibDUnO7MoR'
 || 'HXdDuvgjpzNxgevG+dF/hr3dWfoNyEZ8Taqn+7d7ozmqpGM8zdMYruFrXopVjvY2'
 || 'in9gXe+5vBf1KfX9E6TOVBsb8i5iqwQyv9+a3Gg/Cv+VoDtaQ7xdPwfNYRDji09g'
 || 'X/FvLNGmO62B9jSsoFwgfM+jf1z/SPwrkTMBOkCTBQAEAAA=' );
 --
 init_core_font( 8, 'times', 'BI', 'Times-BoldItalic'
 , 'H4sIAAAAAAAAC8WSuw2DMBCGHegYwEuECajIAGwQ0TBFBnCfPktkAKagzgCRIqWi'
 || 'oso9fr+Qo5RB+nT2ve+wMWYzf+fgjKmOJFelPhENnS0xANJXHfwHSBtjfoI8nMMj'
 || 'tXo63xKW/Cx9ONRn3US6C/wWvYeYNr+LH2IY6cHGPkJfvsc5kX7mFjF+Vqs9iT6d'
 || 'zwEL26y1Qz62nWlvD5VSf4R9zPuon/ne+C45+XxXf5lnTGLTOZCXPx8v9Qfdjdid'
 || '5vD/f/+/pE/Ur14kG+xjTHRc84pZWsC2Hjk2+Hgbx78j4Z8W4DlL+rBnEN5Bie6L'
 || 'fsL+1u/InuYCdsdaeAs+RxftKfGdfQDlDF/kAAQAAA==' );
 --
 init_core_font( 9, 'courier', 'N', 'Courier', null );
 for i in 0 .. 255
 loop
 g_fonts( 9 ).char_width_tab( i ) := 600;
 end loop;
 --
 init_core_font( 10, 'courier', 'I', 'Courier-Oblique', null );
 g_fonts( 10 ).char_width_tab := g_fonts( 9 ).char_width_tab;
 --
 init_core_font( 11, 'courier', 'B', 'Courier-Bold', null );
 g_fonts( 11 ).char_width_tab := g_fonts( 9 ).char_width_tab;
 --
 init_core_font( 12, 'courier', 'BI', 'Courier-BoldOblique', null );
 g_fonts( 12 ).char_width_tab := g_fonts( 9 ).char_width_tab;
 --
 init_core_font( 13, 'symbol', 'N', 'Symbol'
 , 'H4sIAAAAAAAAC82SIU8DQRCFZ28xIE+cqcbha4tENKk/gQCJJ6AweIK9H1CHqKnp'
 || 'D2gTFBaDIcFwCQkJSTG83fem7SU0qYNLvry5nZ25t7NnZkv7c8LQrFhAP6GHZvEY'
 || 'HOB9ylxGubTfNVRc34mKpFonzBQ/gUZ6Ds7AN6i5lv1dKv8Ab1eKQYSV4hUcgZFq'
 || 'J/Sec7fQHtdTn3iqfvdrb7m3e2pZW+xDG3oIJ/Li3gfMr949rlU74DyT1/AuTX1f'
 || 'YGhOzTP8B0/RggsEX/I03vgXPrrslZjfM8/pGu40t2ZjHgud97F7337mXP/GO4h9'
 || '3WmPPaOJ/jrOs9yC52MlrtUzfWupfTX51X/L+13Vl/J/s4W2S3pSfSh5DmeXerMf'
 || '+LXhWQAEAAA=' );
 --
 init_core_font( 14, 'zapfdingbats', 'N', 'ZapfDingbats'
 , 'H4sIAAAAAAAAC83ROy9EQRjG8TkzjdJl163SSHR0EpdsVkSi2UahFhUljUKUIgoq'
 || 'CrvJCtFQyG6EbSSERGxhC0ofQAQFxbIi8T/7PoUPIOEkvzxzzsycdy7O/fUTtToX'
 || 'bnCuvHPOV8gk4r423ovkGQ5od5OTWMeesmBz/RuZIWv4wCAY4z/xjipeqflC9qAD'
 || 'aRwxrxkJievSFzrRh36tZ1zttL6nkGX+A27xrLnttE/IBji9x7UvcIl9nPJ9AL36'
 || 'd1L9hyihoDW10L62cwhNyhntryZVExYl3kMj+zym+CrJv6M8VozPmfr5L8uwJORL'
 || 'tox7NFHG/Obj79FlwhqZ1X292xn6CbAXP/fjjv6rJYyBtUdl1vxEO6fcRB7bMmJ3'
 || 'GYZsTN0GdrDL/Ao5j1GZNr5kwqydX5z1syoiYEq5gCtlSrXi+mVbi3PfVAuhoQAE'
 || 'AAA=' );
 --
 end;
 --
 function to_char_round
 ( p_value number
 , p_precision pls_integer := 2
 )
 return varchar2
 is
 begin
 return to_char( round( p_value, p_precision ), 'TM9', 'NLS_NUMERIC_CHARACTERS=.,' );
 end;
 --
 procedure raw2pdfdoc( p_raw blob )
 is
 begin
 dbms_lob.append( g_pdf_doc, p_raw );
 end;
 --
 procedure txt2pdfdoc( p_txt varchar2 )
 is
 begin
 raw2pdfdoc( utl_raw.cast_to_raw( p_txt || c_nl ) );
 end;
 --
 function add_object( p_txt varchar2 := null )
 return number
 is
 t_self number(10);
 begin
 t_self := g_objects.count( );
 g_objects( t_self ) := dbms_lob.getlength( g_pdf_doc );
 --
 if p_txt is null
 then
 txt2pdfdoc( t_self || ' 0 obj' );
 else
 txt2pdfdoc( t_self || ' 0 obj' || c_nl || '<<' || p_txt || '>>' || c_nl || 'endobj' );
 end if;
 --
 return t_self;
 end;
 --
 procedure add_object( p_txt varchar2 := null )
 is
 t_dummy number(10) := add_object( p_txt );
 begin
 null;
 end;
 --
 function adler32( p_src in blob )
 return varchar2
 is
 s1 pls_integer := 1;
 s2 pls_integer := 0;
 n pls_integer;
 step_size number;
 tmp varchar2(32766);
 c65521 constant pls_integer := 65521;
 begin
 step_size := trunc( 16383 / dbms_lob.getchunksize( p_src ) ) * dbms_lob.getchunksize( p_src );
 for j in 0 .. trunc( ( dbms_lob.getlength( p_src ) - 1 ) / step_size )
 loop
 tmp := rawtohex( dbms_lob.substr( p_src, step_size, j * step_size + 1 ) );
 for i in 1 .. length( tmp ) / 2
 loop
 n := to_number( substr( tmp, i * 2 - 1, 2 ), 'xx' );
 s1 := s1 + n;
 if s1 >= c65521
 then
 s1 := s1 - c65521;
 end if;
 s2 := s2 + s1;
 if s2 >= c65521
 then
 s2 := s2 - c65521;
 end if;
 end loop;
 end loop;
 return to_char( s2, 'fm0XXX' ) || to_char( s1, 'fm0XXX' );
 end;
 --
 function flate_encode( p_val blob )
 return blob
 is
 t_blob blob;
 begin
 t_blob := hextoraw( '789C' );
 dbms_lob.copy( t_blob
 , utl_compress.lz_compress( p_val )
 , dbms_lob.lobmaxsize
 , 3
 , 11
 );
 dbms_lob.trim( t_blob, dbms_lob.getlength( t_blob ) - 8 );
 dbms_lob.append( t_blob, hextoraw( adler32( p_val ) ) );
 return t_blob;
 end;
 --
 procedure put_stream
 ( p_stream blob
 , p_compress boolean := true
 , p_extra varchar2 := ''
 , p_tag boolean := true
 )
 is
 t_blob blob;
 t_compress boolean := false;
 begin
 if p_compress and nvl( dbms_lob.getlength( p_stream ), 0 ) > 0
 then
 t_compress := true;
 t_blob := flate_encode( p_stream );
 else
 t_blob := p_stream;
 end if;
 txt2pdfdoc( case when p_tag then '<<' end
 || case when t_compress then '/Filter /FlateDecode ' end
 || '/Length ' || nvl( length( t_blob ), 0 )
 || p_extra
 || '>>' );
 txt2pdfdoc( 'stream' );
 raw2pdfdoc( t_blob );
 txt2pdfdoc( 'endstream' );
 if dbms_lob.istemporary( t_blob ) = 1
 then
 dbms_lob.freetemporary( t_blob );
 end if;
 end;
 --
 function add_stream
 ( p_stream blob
 , p_extra varchar2 := ''
 , p_compress boolean := true
 )
 return number
 is
 t_self number(10);
 begin
 t_self := add_object;
 put_stream( p_stream
 , p_compress
 , p_extra
 );
 txt2pdfdoc( 'endobj' );
 return t_self;
 end;
 --
 function subset_font( p_index pls_integer )
 return blob
 is
 t_tmp blob;
 t_header blob;
 t_tables blob;
 t_len pls_integer;
 t_code pls_integer;
 t_glyph pls_integer;
 t_offset pls_integer;
 t_factor pls_integer;
 t_unicode pls_integer;
 t_used_glyphs tp_pls_tab;
 t_fmt varchar2(10);
 t_utf16_charset varchar2(1000);
 t_raw raw(32767);
 t_v varchar2(32767);
 t_table_records raw(32767);
 begin
 if g_fonts( p_index ).cid
 then
 t_used_glyphs := g_fonts( p_index ).used_chars;
 t_used_glyphs( 0 ) := 0;
 else
 t_utf16_charset := substr( g_fonts( p_index ).charset, 1, instr( g_fonts( p_index ).charset, '.' ) ) || 'AL16UTF16';
 t_used_glyphs( 0 ) := 0;
 t_code := g_fonts( p_index ).used_chars.first;
 while t_code is not null
 loop
 t_unicode := to_number( rawtohex( utl_raw.convert( hextoraw( to_char( t_code, 'fm0x' ) )
 , t_utf16_charset
 , g_fonts( p_index ).charset -- ???? database characterset ?????
 )
 ), 'XXXXXXXX' );
 if g_fonts( p_index ).flags = 4 -- a symbolic font
 then
 -- assume code 32, space maps to the first code from the font
 t_used_glyphs( g_fonts( p_index ).code2glyph( g_fonts( p_index ).code2glyph.first + t_unicode - 32 ) ) := 0;
 else
 t_used_glyphs( g_fonts( p_index ).code2glyph( t_unicode ) ) := 0;
 end if;
 t_code := g_fonts( p_index ).used_chars.next( t_code );
 end loop;
 end if;
 --
 dbms_lob.createtemporary( t_tables, true );
 t_header := utl_raw.concat( hextoraw( '00010000' )
 , dbms_lob.substr( g_fonts( p_index ).fontfile2, 8, g_fonts( p_index ).ttf_offset + 4 )
 );
 t_offset := 12 + blob2num( g_fonts( p_index ).fontfile2, 2, g_fonts( p_index ).ttf_offset + 4 ) * 16;
 t_table_records := dbms_lob.substr( g_fonts( p_index ).fontfile2
 , blob2num( g_fonts( p_index ).fontfile2, 2, g_fonts( p_index ).ttf_offset + 4 ) * 16
 , g_fonts( p_index ).ttf_offset + 12
 );
 for i in 1 .. blob2num( g_fonts( p_index ).fontfile2, 2, g_fonts( p_index ).ttf_offset + 4 )
 loop
 case utl_raw.cast_to_varchar2( utl_raw.substr( t_table_records, i * 16 - 15, 4 ) )
 when 'post'
 then
 dbms_lob.append( t_header
 , utl_raw.concat( utl_raw.substr( t_table_records, i * 16 - 15, 4 ) -- tag
 , hextoraw( '00000000' ) -- checksum
 , num2raw( t_offset + dbms_lob.getlength( t_tables ) ) -- offset
 , num2raw( 32 ) -- length
 )
 );
 dbms_lob.append( t_tables
 , utl_raw.concat( hextoraw( '00030000' )
 , dbms_lob.substr( g_fonts( p_index ).fontfile2
 , 28
 , raw2num( t_table_records, i * 16 - 7, 4 ) + 5
 )
 )
 );
 when 'loca'
 then
 if g_fonts( p_index ).indexToLocFormat = 0
 then
 t_fmt := 'fm0XXX';
 else
 t_fmt := 'fm0XXXXXXX';
 end if;
 t_raw := null;
 dbms_lob.createtemporary( t_tmp, true );
 t_len := 0;
 for g in 0 .. g_fonts( p_index ).numGlyphs - 1
 loop
 t_raw := utl_raw.concat( t_raw, hextoraw( to_char( t_len, t_fmt ) ) );
 if utl_raw.length( t_raw ) > 32770
 then
 dbms_lob.append( t_tmp, t_raw );
 t_raw := null;
 end if;
 if t_used_glyphs.exists( g )
 then
 t_len := t_len + g_fonts( p_index ).loca( g + 1 ) - g_fonts( p_index ).loca( g );
 end if;
 end loop;
 t_raw := utl_raw.concat( t_raw, hextoraw( to_char( t_len, t_fmt ) ) );
 dbms_lob.append( t_tmp, t_raw );
 dbms_lob.append( t_header
 , utl_raw.concat( utl_raw.substr( t_table_records, i * 16 - 15, 4 ) -- tag
 , hextoraw( '00000000' ) -- checksum
 , num2raw( t_offset + dbms_lob.getlength( t_tables ) ) -- offset
 , num2raw( dbms_lob.getlength( t_tmp ) ) -- length
 )
 );
 dbms_lob.append( t_tables, t_tmp );
 dbms_lob.freetemporary( t_tmp );
 when 'glyf'
 then
 if g_fonts( p_index ).indexToLocFormat = 0
 then
 t_factor := 2;
 else
 t_factor := 1;
 end if;
 t_raw := null;
 dbms_lob.createtemporary( t_tmp, true );
 for g in 0 .. g_fonts( p_index ).numGlyphs - 1
 loop
 if ( t_used_glyphs.exists( g )
 and g_fonts( p_index ).loca( g + 1 ) > g_fonts( p_index ).loca( g )
 )
 then
 t_raw := utl_raw.concat( t_raw
 , dbms_lob.substr( g_fonts( p_index ).fontfile2
 , ( g_fonts( p_index ).loca( g + 1 ) - g_fonts( p_index ).loca( g ) ) * t_factor
 , g_fonts( p_index ).loca( g ) * t_factor + raw2num( t_table_records, i * 16 - 7, 4 ) + 1
 )
 );
 if utl_raw.length( t_raw ) > 32778
 then
 dbms_lob.append( t_tmp, t_raw );
 t_raw := null;
 end if;
 end if;
 end loop;
 if utl_raw.length( t_raw ) > 0
 then
 dbms_lob.append( t_tmp, t_raw );
 end if;
 dbms_lob.append( t_header
 , utl_raw.concat( utl_raw.substr( t_table_records, i * 16 - 15, 4 ) -- tag
 , hextoraw( '00000000' ) -- checksum
 , num2raw( t_offset + dbms_lob.getlength( t_tables ) ) -- offset
 , num2raw( dbms_lob.getlength( t_tmp ) ) -- length
 )
 );
 dbms_lob.append( t_tables, t_tmp );
 dbms_lob.freetemporary( t_tmp );
 else
 dbms_lob.append( t_header
 , utl_raw.concat( utl_raw.substr( t_table_records, i * 16 - 15, 4 ) -- tag
 , utl_raw.substr( t_table_records, i * 16 - 11, 4 ) -- checksum
 , num2raw( t_offset + dbms_lob.getlength( t_tables ) ) -- offset
 , utl_raw.substr( t_table_records, i * 16 - 3, 4 ) -- length
 )
 );
 dbms_lob.copy( t_tables
 , g_fonts( p_index ).fontfile2
 , raw2num( t_table_records, i * 16 - 3, 4 )
 , dbms_lob.getlength( t_tables ) + 1
 , raw2num( t_table_records, i * 16 - 7, 4 ) + 1
 );
 end case;
 end loop;
 dbms_lob.append( t_header, t_tables );
 dbms_lob.freetemporary( t_tables );
 return t_header;
 end;
 --
 function add_font( p_index pls_integer )
 return number
 is
 t_self number(10);
 t_fontfile number(10);
 t_font_subset blob;
 t_used pls_integer;
 t_used_glyphs tp_pls_tab;
 t_w varchar2(32767);
 t_unicode pls_integer;
 t_utf16_charset varchar2(1000);
 t_width number;
 begin
 if g_fonts( p_index ).standard
 then
 return add_object( '/Type/Font'
 || '/Subtype/Type1'
 || '/BaseFont/' || g_fonts( p_index ).name
 || '/Encoding/WinAnsiEncoding' -- code page 1252
 );
 end if;
 --
 if g_fonts( p_index ).cid
 then
 t_self := add_object;
 txt2pdfdoc( '<</Type/Font/Subtype/Type0/Encoding/Identity-H'
 || '/BaseFont/' || g_fonts( p_index ).name
 || '/DescendantFonts ' || to_char( t_self + 1 ) || ' 0 R'
 || '/ToUnicode ' || to_char( t_self + 8 ) || ' 0 R'
 || '>>' );
 txt2pdfdoc( 'endobj' );
 add_object;
 txt2pdfdoc( '[' || to_char( t_self + 2 ) || ' 0 R]' );
 txt2pdfdoc( 'endobj' );
 add_object( '/Type/Font/Subtype/CIDFontType2/CIDToGIDMap/Identity/DW 1000'
 || '/BaseFont/' || g_fonts( p_index ).name
 || '/CIDSystemInfo ' || to_char( t_self + 3 ) || ' 0 R'
 || '/W ' || to_char( t_self + 4 ) || ' 0 R'
 || '/FontDescriptor ' || to_char( t_self + 5 ) || ' 0 R' );
 add_object( '/Ordering(Identity) /Registry(Adobe) /Supplement 0' );
 --
 t_utf16_charset := substr( g_fonts( p_index ).charset, 1, instr( g_fonts( p_index ).charset, '.' ) ) || 'AL16UTF16';
 t_used_glyphs := g_fonts( p_index ).used_chars;
 t_used_glyphs( 0 ) := 0;
 t_used := t_used_glyphs.first();
 while t_used is not null
 loop
 if g_fonts( p_index ).hmetrics.exists( t_used )
 then
 t_width := g_fonts( p_index ).hmetrics( t_used );
 else
 t_width := g_fonts( p_index ).hmetrics( g_fonts( p_index ).hmetrics.last() );
 end if;
 t_width := trunc( t_width * g_fonts( p_index ).unit_norm );
 if t_used_glyphs.prior( t_used ) = t_used - 1
 then
 t_w := t_w || ' ' || t_width;
 else
 t_w := t_w || '] ' || t_used || ' [' || t_width;
 end if;
 t_used := t_used_glyphs.next( t_used );
 end loop;
 t_w := '[' || ltrim( t_w, '] ' ) || ']]';
 add_object;
 txt2pdfdoc( t_w );
 txt2pdfdoc( 'endobj' );
 add_object
 ( '/Type/FontDescriptor'
 || '/FontName/' || g_fonts( p_index ).name
 || '/Flags ' || g_fonts( p_index ).flags
 || '/FontBBox [' || g_fonts( p_index ).bb_xmin
 || ' ' || g_fonts( p_index ).bb_ymin
 || ' ' || g_fonts( p_index ).bb_xmax
 || ' ' || g_fonts( p_index ).bb_ymax
 || ']'
 || '/ItalicAngle ' || to_char_round( g_fonts( p_index ).italic_angle )
 || '/Ascent ' || g_fonts( p_index ).ascent
 || '/Descent ' || g_fonts( p_index ).descent
 || '/CapHeight ' || g_fonts( p_index ).capheight
 || '/StemV ' || g_fonts( p_index ).stemv
 || '/FontFile2 ' || to_char( t_self + 6 ) || ' 0 R' );
 t_fontfile := add_stream( g_fonts( p_index ).fontfile2
 , '/Length1 ' || dbms_lob.getlength( g_fonts( p_index ).fontfile2 )
 , g_fonts( p_index ).compress_font
 );
 t_font_subset := subset_font( p_index );
 t_fontfile := add_stream( t_font_subset
 , '/Length1 ' || dbms_lob.getlength( t_font_subset )
 , g_fonts( p_index ).compress_font
 );
 declare
 t_g2c tp_pls_tab;
 t_code pls_integer;
 t_c_start pls_integer;
 t_map varchar2(32767);
 t_cmap varchar2(32767);
 t_cor pls_integer;
 t_cnt pls_integer;
 begin
 t_code := g_fonts( p_index ).code2glyph.first;
 if g_fonts( p_index ).flags = 4 -- a symbolic font
 then
 -- assume code 32, space maps to the first code from the font
 t_cor := t_code - 32;
 else
 t_cor := 0;
 end if;
 while t_code is not null
 loop
 t_g2c( g_fonts( p_index ).code2glyph( t_code ) ) := t_code - t_cor;
 t_code := g_fonts( p_index ).code2glyph.next( t_code );
 end loop;
 t_cnt := 0;
 t_used_glyphs := g_fonts( p_index ).used_chars;
 t_used := t_used_glyphs.first();
 while t_used is not null
 loop
 t_map := t_map || '<' || to_char( t_used, 'FM0XXX' )
 || '> <' || to_char( t_g2c( t_used ), 'FM0XXX' )
 || '>' || chr( 10 );
 if t_cnt = 99
 then
 t_cnt := 0;
 t_cmap := t_cmap || chr( 10 ) || '100 beginbfchar' || chr( 10 ) || t_map || 'endbfchar';
 t_map := '';
 else
 t_cnt := t_cnt + 1;
 end if;
 t_used := t_used_glyphs.next( t_used );
 end loop;
 if t_cnt > 0
 then
 t_cmap := t_cnt || ' beginbfchar' || chr( 10 ) || t_map || 'endbfchar';
 end if;
 t_fontfile := add_stream( utl_raw.cast_to_raw(
 '/CIDInit /ProcSet findresource begin 12 dict begin
 begincmap
 /CIDSystemInfo
 << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def
 /CMapName /Adobe-Identity-UCS def /CMapType 2 def
 1 begincodespacerange
 <0000> <FFFF>
 endcodespacerange
 ' || t_cmap || '
 endcmap
 CMapName currentdict /CMap defineresource pop
 end
 end' ) );
 end;
 return t_self;
 end if;
 --
 g_fonts( p_index ).first_char := g_fonts( p_index ).used_chars.first();
 g_fonts( p_index ).last_char := g_fonts( p_index ).used_chars.last();
 t_self := add_object;
 txt2pdfdoc( '<</Type /Font '
 || '/Subtype /' || g_fonts( p_index ).subtype
 || ' /BaseFont /' || g_fonts( p_index ).name
 || ' /FirstChar ' || g_fonts( p_index ).first_char
 || ' /LastChar ' || g_fonts( p_index ).last_char
 || ' /Widths ' || to_char( t_self + 1 ) || ' 0 R'
 || ' /FontDescriptor ' || to_char( t_self + 2 ) || ' 0 R'
 || ' /Encoding ' || to_char( t_self + 3 ) || ' 0 R'
 || ' >>' );
 txt2pdfdoc( 'endobj' );
 add_object;
 txt2pdfdoc( '[' );
 begin
 for i in g_fonts( p_index ).first_char .. g_fonts( p_index ).last_char
 loop
 txt2pdfdoc( g_fonts( p_index ).char_width_tab( i ) );
 end loop;
 exception
 when others
 then
 dbms_output.put_line( '**** ' || g_fonts( p_index ).name );
 end;
 txt2pdfdoc( ']' );
 txt2pdfdoc( 'endobj' );
 add_object
 ( '/Type /FontDescriptor'
 || ' /FontName /' || g_fonts( p_index ).name
 || ' /Flags ' || g_fonts( p_index ).flags
 || ' /FontBBox [' || g_fonts( p_index ).bb_xmin
 || ' ' || g_fonts( p_index ).bb_ymin
 || ' ' || g_fonts( p_index ).bb_xmax
 || ' ' || g_fonts( p_index ).bb_ymax
 || ']'
 || ' /ItalicAngle ' || to_char_round( g_fonts( p_index ).italic_angle )
 || ' /Ascent ' || g_fonts( p_index ).ascent
 || ' /Descent ' || g_fonts( p_index ).descent
 || ' /CapHeight ' || g_fonts( p_index ).capheight
 || ' /StemV ' || g_fonts( p_index ).stemv
 || case
 when g_fonts( p_index ).fontfile2 is not null
 then ' /FontFile2 ' || to_char( t_self + 4 ) || ' 0 R'
 end );
 add_object( '/Type /Encoding /BaseEncoding /WinAnsiEncoding '
 || g_fonts( p_index ).diff
 || ' ' );
 if g_fonts( p_index ).fontfile2 is not null
 then
 t_font_subset := subset_font( p_index );
 t_fontfile :=
 add_stream( t_font_subset
 , '/Length1 ' || dbms_lob.getlength( t_font_subset )
 , g_fonts( p_index ).compress_font
 );
 end if;
 return t_self;
 end;
 --
 procedure add_image( p_img tp_img )
 is
 t_pallet number(10);
 begin
 if p_img.color_tab is not null
 then
 t_pallet := add_stream( p_img.color_tab );
 else
 t_pallet := add_object; -- add an empty object
 txt2pdfdoc( 'endobj' );
 end if;
 add_object;
 txt2pdfdoc( '<</Type /XObject /Subtype /Image'
 || ' /Width ' || to_char( p_img.width )
 || ' /Height ' || to_char( p_img.height )
 || ' /BitsPerComponent ' || to_char( p_img.color_res )
 );
 --
 if p_img.transparancy_index is not null
 then
 txt2pdfdoc( '/Mask [' || p_img.transparancy_index || ' ' || p_img.transparancy_index || ']' );
 end if;
 if p_img.color_tab is null
 then
 if p_img.greyscale
 then
 txt2pdfdoc( '/ColorSpace /DeviceGray' );
 else
 txt2pdfdoc( '/ColorSpace /DeviceRGB' );
 end if;
 else
 txt2pdfdoc( '/ColorSpace [/Indexed /DeviceRGB '
 || to_char( utl_raw.length( p_img.color_tab ) / 3 - 1 )
 || ' ' || to_char( t_pallet ) || ' 0 R]'
 );
 end if;
 --
 if p_img.type = 'jpg'
 then
 put_stream( p_img.pixels, false, '/Filter /DCTDecode', false );
 elsif p_img.type = 'png'
 then
 put_stream( p_img.pixels, false
 , ' /Filter /FlateDecode /DecodeParms <</Predictor 15 '
 || '/Colors ' || p_img.nr_colors
 || '/BitsPerComponent ' || p_img.color_res
 || ' /Columns ' || p_img.width
 || ' >> '
 , false );
 else
 put_stream( p_img.pixels, p_tag => false );
 end if;
 txt2pdfdoc( 'endobj' );
 end;
 --
 function add_resources
 return number
 is
 t_ind pls_integer;
 t_self number(10);
 t_fonts tp_objects_tab;
 begin
 --
 t_ind := g_used_fonts.first;
 while t_ind is not null
 loop
 t_fonts( t_ind ) := add_font( t_ind );
 t_ind := g_used_fonts.next( t_ind );
 end loop;
 --
 t_self := add_object;
 txt2pdfdoc( '<</ProcSet [/PDF /Text]' );
 --
 if g_used_fonts.count() > 0
 then
 txt2pdfdoc( '/Font <<' );
 t_ind := g_used_fonts.first;
 while t_ind is not null
 loop
 txt2pdfdoc( '/F'|| to_char( t_ind ) || ' '
 || to_char( t_fonts( t_ind ) ) || ' 0 R'
 );
 t_ind := g_used_fonts.next( t_ind );
 end loop;
 txt2pdfdoc( '>>' );
 end if;
 --
 if g_images.count( ) > 0
 then
 txt2pdfdoc( '/XObject <<' );
 for i in g_images.first .. g_images.last
 loop
 txt2pdfdoc( '/I' || to_char( i ) || ' ' || to_char( t_self + 2 * i ) || ' 0 R' );
 end loop;
 txt2pdfdoc( '>>' );
 end if;
 --
 txt2pdfdoc( '>>' );
 txt2pdfdoc( 'endobj' );
 --
 if g_images.count( ) > 0
 then
 for i in g_images.first .. g_images.last
 loop
 add_image( g_images( i ) );
 end loop;
 end if;
 return t_self;
 end;
 --
 procedure add_page
 ( p_page_ind pls_integer
 , p_parent number
 , p_resources number
 )
 is
 t_content number(10);
 begin
 t_content := add_stream( g_pages( p_page_ind ) );
 add_object;
 txt2pdfdoc( '<< /Type /Page' );
 txt2pdfdoc( '/Parent ' || to_char( p_parent ) || ' 0 R' );
 txt2pdfdoc( '/Contents ' || to_char( t_content ) || ' 0 R' );
 txt2pdfdoc( '/Resources ' || to_char( p_resources ) || ' 0 R' );
 txt2pdfdoc( '>>' );
 txt2pdfdoc( 'endobj' );
 end;
 --
 function add_pages
 return number
 is
 t_self number(10);
 t_resources number(10);
 begin
 t_resources := add_resources;
 t_self := add_object;
 txt2pdfdoc( '<</Type/Pages/Kids [' );
 --
 for i in g_pages.first .. g_pages.last
 loop
 txt2pdfdoc( to_char( t_self + i * 2 + 2 ) || ' 0 R' );
 end loop;
 --
 txt2pdfdoc( ']' );
 txt2pdfdoc( '/Count ' || g_pages.count() );
 txt2pdfdoc( '/MediaBox [0 0 '
 || to_char_round( g_settings.page_width
 , 0
 )
 || ' '
 || to_char_round( g_settings.page_height
 , 0
 )
 || ']' );
 txt2pdfdoc( '>>' );
 txt2pdfdoc( 'endobj' );
 --
 if g_pages.count() > 0
 then
 for i in g_pages.first .. g_pages.last
 loop
 add_page( i, t_self, t_resources );
 end loop;
 end if;
 --
 return t_self;
 end;
 --
 function add_catalogue
 return number
 is
 begin
 return add_object( '/Type/Catalog'
 || '/Pages ' || to_char( add_pages ) || ' 0 R'
 || '/OpenAction [0 /XYZ null null 0.77]'
 );
 end;
 --
 function add_info
 return number
 is
 t_banner varchar2( 1000 );
 begin
 begin
 select 'running on '
 || replace( replace( replace( substr( banner
 , 1
 , 950
 )
 , '\'
 , '\\'
 )
 , '('
 , '\('
 )
 , ')'
 , '\)'
 )
 into t_banner
 from v$version
 where instr( upper( banner )
 , 'DATABASE'
 ) > 0;
 t_banner := '/Producer (' || t_banner || ')';
 exception
 when others
 then
 null;
 end;
 --
 return add_object( to_char( sysdate, '"/CreationDate (D:"YYYYMMDDhh24miss")"' )
 || '/Creator (AS-PDF 0.3.0 by Anton Scheffer)'
 || t_banner
 || '/Title <FEFF' || utl_i18n.string_to_raw( g_info.title, 'AL16UTF16' ) || '>'
 || '/Author <FEFF' || utl_i18n.string_to_raw( g_info.author, 'AL16UTF16' ) || '>'
 || '/Subject <FEFF' || utl_i18n.string_to_raw( g_info.subject, 'AL16UTF16' ) || '>'
 || '/Keywords <FEFF' || utl_i18n.string_to_raw( g_info.keywords, 'AL16UTF16' ) || '>'
 );
 end;
 --
 procedure finish_pdf
 is
 t_xref number;
 t_info number(10);
 t_catalogue number(10);
 begin
 if g_pages.count = 0
 then
 new_page;
 end if;
 if g_page_prcs.count > 0
 then
 for i in g_pages.first .. g_pages.last
 loop
 g_page_nr := i;
 for p in g_page_prcs.first .. g_page_prcs.last
 loop
 begin
 execute immediate replace( replace( g_page_prcs( p ), '#PAGE_NR#', i + 1 ), '"PAGE_COUNT#', g_pages.count );
 exception
 when others then null;
 end;
 end loop;
 end loop;
 end if;
 dbms_lob.createtemporary( g_pdf_doc, true );
 txt2pdfdoc( '%PDF-1.3' );
 raw2pdfdoc( hextoraw( '25E2E3CFD30D0A' ) ); -- add a hex comment
 t_info := add_info;
 t_catalogue := add_catalogue;
 t_xref := dbms_lob.getlength( g_pdf_doc );
 txt2pdfdoc( 'xref' );
 txt2pdfdoc( '0 ' || to_char( g_objects.count() ) );
 txt2pdfdoc( '0000000000 65535 f ' );
 for i in 1 .. g_objects.count( ) - 1
 loop
 txt2pdfdoc( to_char( g_objects( i ), 'fm0000000000' ) || ' 00000 n' );
 -- this line should be exactly 20 bytes, including EOL
 end loop;
 txt2pdfdoc( 'trailer' );
 txt2pdfdoc( '<< /Root ' || to_char( t_catalogue ) || ' 0 R' );
 txt2pdfdoc( '/Info ' || to_char( t_info ) || ' 0 R' );
 txt2pdfdoc( '/Size ' || to_char( g_objects.count() ) );
 txt2pdfdoc( '>>' );
 txt2pdfdoc( 'startxref' );
 txt2pdfdoc( to_char( t_xref ) );
 txt2pdfdoc( '%%EOF' );
 --
 g_objects.delete;
 for i in g_pages.first .. g_pages.last
 loop
 dbms_lob.freetemporary( g_pages( i ) );
 end loop;
 g_objects.delete;
 g_pages.delete;
 g_fonts.delete;
 g_used_fonts.delete;
 g_page_prcs.delete;
 if g_images.count() > 0
 then
 for i in g_images.first .. g_images.last
 loop
 if dbms_lob.istemporary( g_images( i ).pixels ) = 1
 then
 dbms_lob.freetemporary( g_images( i ).pixels );
 end if;
 end loop;
 g_images.delete;
 end if;
 end;
 --
 function conv2uu( p_value number, p_unit varchar2 )
 return number
 is
 c_inch constant number := 25.40025;
 begin
 return round( case lower( p_unit )
 when 'mm' then p_value * 72 / c_inch
 when 'cm' then p_value * 720 / c_inch
 when 'pt' then p_value -- also point
 when 'point' then p_value
 when 'inch' then p_value * 72
 when 'in' then p_value * 72 -- also inch
 when 'pica' then p_value * 12
 when 'p' then p_value * 12 -- also pica
 when 'pc' then p_value * 12 -- also pica
 when 'em' then p_value * 12 -- also pica
 when 'px' then p_value -- pixel voorlopig op point zetten
 when 'px' then p_value * 0.8 -- pixel
 else null
 end
 , 3
 );
 end;
 --
 procedure set_page_size
 ( p_width number
 , p_height number
 , p_unit varchar2 := 'cm'
 )
 is
 begin
 g_settings.page_width := conv2uu( p_width, p_unit );
 g_settings.page_height := conv2uu( p_height, p_unit );
 end;
 --
 procedure set_page_format( p_format varchar2 := 'A4' )
 is
 begin
 case upper( p_format )
 when 'A3'
 then
 set_page_size( 420, 297, 'mm' );
 when 'A4'
 then
 set_page_size( 297, 210, 'mm' );
 when 'A5'
 then
 set_page_size( 210, 148, 'mm' );
 when 'A6'
 then
 set_page_size( 148, 105, 'mm' );
 when 'LEGAL'
 then
 set_page_size( 14, 8.5, 'in' );
 when 'LETTER'
 then
 set_page_size( 11, 8.5, 'in' );
 when 'QUARTO'
 then
 set_page_size( 11, 9, 'in' );
 when 'EXECUTIVE'
 then
 set_page_size( 10.5, 7.25, 'in' );
 else
 null;
 end case;
 end;
 --
 procedure set_page_orientation( p_orientation varchar2 := 'PORTRAIT' )
 is
 t_tmp number;
 begin
 if ( ( upper( p_orientation ) in ( 'L', 'LANDSCAPE' )
 and g_settings.page_height > g_settings.page_width
 )
 or ( upper( p_orientation ) in( 'P', 'PORTRAIT' )
 and g_settings.page_height < g_settings.page_width
 )
 )
 then
 t_tmp := g_settings.page_width;
 g_settings.page_width := g_settings.page_height;
 g_settings.page_height := t_tmp;
 end if;
 end;
 --
 procedure set_margins
 ( p_top number := null
 , p_left number := null
 , p_bottom number := null
 , p_right number := null
 , p_unit varchar2 := 'cm'
 )
 is
 t_tmp number;
 begin
 t_tmp := nvl( conv2uu( p_top, p_unit ), -1 );
 if t_tmp < 0 or t_tmp > g_settings.page_height
 then
 t_tmp := conv2uu( 3, 'cm' );
 end if;
 g_settings.margin_top := t_tmp;
 t_tmp := nvl( conv2uu( p_bottom, p_unit ), -1 );
 if t_tmp < 0 or t_tmp > g_settings.page_height
 then
 t_tmp := conv2uu( 4, 'cm' );
 end if;
 g_settings.margin_bottom := t_tmp;
 t_tmp := nvl( conv2uu( p_left, p_unit ), -1 );
 if t_tmp < 0 or t_tmp > g_settings.page_width
 then
 t_tmp := conv2uu( 1, 'cm' );
 end if;
 g_settings.margin_left := t_tmp;
 t_tmp := nvl( conv2uu( p_right, p_unit ), -1 );
 if t_tmp < 0 or t_tmp > g_settings.page_width
 then
 t_tmp := conv2uu( 1, 'cm' );
 end if;
 g_settings.margin_right := t_tmp;
 --
 if g_settings.margin_top + g_settings.margin_bottom + conv2uu( 1, 'cm' )> g_settings.page_height
 then
 g_settings.margin_top := 0;
 g_settings.margin_bottom := 0;
 end if;
 if g_settings.margin_left + g_settings.margin_right + conv2uu( 1, 'cm' )> g_settings.page_width
 then
 g_settings.margin_left := 0;
 g_settings.margin_right := 0;
 end if;
 end;
 --
 procedure set_info
 ( p_title varchar2 := null
 , p_author varchar2 := null
 , p_subject varchar2 := null
 , p_keywords varchar2 := null
 )
 is
 begin
 g_info.title := substr( p_title, 1, 1024 );
 g_info.author := substr( p_author, 1, 1024 );
 g_info.subject := substr( p_subject, 1, 1024 );
 g_info.keywords := substr( p_keywords, 1, 16383 );
 end;
 --
 procedure init
 is
 begin
 g_objects.delete;
 g_pages.delete;
 g_fonts.delete;
 g_used_fonts.delete;
 g_page_prcs.delete;
 g_images.delete;
 g_settings := null;
 g_current_font := null;
 g_x := null;
 g_y := null;
 g_info := null;
 g_page_nr := null;
 g_objects( 0 ) := 0;
 init_core_fonts;
 set_page_format;
 set_page_orientation;
 set_margins;
 end;
 --
 function get_pdf
 return blob
 is
 begin
 finish_pdf;
 return g_pdf_doc;
 end;
 --
 procedure save_pdf
 ( p_dir varchar2 := 'MY_DIR'
 , p_filename varchar2 := 'my.pdf'
 , p_freeblob boolean := true
 )
 is
 t_fh utl_file.file_type;
 t_len pls_integer := 32767;
 begin
 finish_pdf;
 t_fh := utl_file.fopen( p_dir, p_filename, 'wb' );
 for i in 0 .. trunc( ( dbms_lob.getlength( g_pdf_doc ) - 1 ) / t_len )
 loop
 utl_file.put_raw( t_fh
 , dbms_lob.substr( g_pdf_doc
 , t_len
 , i * t_len + 1
 )
 );
 end loop;
 utl_file.fclose( t_fh );
 if p_freeblob
 then
 dbms_lob.freetemporary( g_pdf_doc );
 end if;
 end;
 --
 procedure raw2page( p_txt blob )
 is
 begin
 if g_pages.count() = 0
 then
 new_page;
 end if;
 dbms_lob.append( g_pages( coalesce( g_page_nr, g_pages.count( ) - 1 ) )
 , utl_raw.concat( p_txt, hextoraw( '0D0A' ) )
 );
 end;
 --
 procedure txt2page( p_txt varchar2 )
 is
 begin
 raw2page( utl_raw.cast_to_raw( p_txt ) );
 end;
 --
 procedure output_font_to_doc( p_output_to_doc boolean )
 is
 begin
 if p_output_to_doc
 then
 txt2page( 'BT /F' || g_current_font || ' '
 || to_char_round( g_fonts( g_current_font ).fontsize ) || ' Tf ET'
 );
 end if;
 end;
 --
 procedure set_font
 ( p_index pls_integer
 , p_fontsize_pt number
 , p_output_to_doc boolean := true
 )
 is
 begin
 if p_index is not null
 then
 g_used_fonts( p_index ) := 0;
 g_current_font := p_index;
 g_fonts( p_index ).fontsize := p_fontsize_pt;
 output_font_to_doc( p_output_to_doc );
 end if;
 end;
 --
 function set_font
 ( p_fontname varchar2
 , p_fontsize_pt number
 , p_output_to_doc boolean := true
 )
 return pls_integer
 is
 t_fontname varchar2(100);
 begin
 if p_fontname is null
 then
 if ( g_current_font is not null
 and p_fontsize_pt != g_fonts( g_current_font ).fontsize
 )
 then
 g_fonts( g_current_font ).fontsize := p_fontsize_pt;
 output_font_to_doc( p_output_to_doc );
 end if;
 return g_current_font;
 end if;
 --
 t_fontname := lower( p_fontname );
 for i in g_fonts.first .. g_fonts.last
 loop
 if lower( g_fonts( i ).fontname ) = t_fontname
 then
 exit when g_current_font = i and g_fonts( i ).fontsize = p_fontsize_pt and g_page_nr is null;
 g_fonts( i ).fontsize := coalesce( p_fontsize_pt
 , g_fonts( nvl( g_current_font, i ) ).fontsize
 , 12
 );
 g_current_font := i;
 g_used_fonts( i ) := 0;
 output_font_to_doc( p_output_to_doc );
 return g_current_font;
 end if;
 end loop;
 return null;
 end;
 --
 procedure set_font
 ( p_fontname varchar2
 , p_fontsize_pt number
 , p_output_to_doc boolean := true
 )
 is
 t_dummy pls_integer;
 begin
 t_dummy := set_font( p_fontname, p_fontsize_pt, p_output_to_doc );
 end;
 --
 function set_font
 ( p_family varchar2
 , p_style varchar2 := 'N'
 , p_fontsize_pt number := null
 , p_output_to_doc boolean := true
 )
 return pls_integer
 is
 t_family varchar2(100);
 t_style varchar2(100);
 begin
 if p_family is null and g_current_font is null
 then
 return null;
 end if;
 if p_family is null and p_style is null and p_fontsize_pt is null
 then
 return null;
 end if;
 t_family := coalesce( lower( p_family )
 , g_fonts( g_current_font ).family
 );
 t_style := upper( p_style );
 t_style := case t_style
 when 'NORMAL' then 'N'
 when 'REGULAR' then 'N'
 when 'BOLD' then 'B'
 when 'ITALIC' then 'I'
 when 'OBLIQUE' then 'I'
 else t_style
 end;
 t_style := coalesce( t_style
 , case when g_current_font is null then 'N' else g_fonts( g_current_font ).style end
 );
 --
 for i in g_fonts.first .. g_fonts.last
 loop
 if ( g_fonts( i ).family = t_family
 and g_fonts( i ).style = t_style
 )
 then
 return set_font( g_fonts( i ).fontname, p_fontsize_pt, p_output_to_doc );
 end if;
 end loop;
 return null;
 end;
 --
 procedure set_font
 ( p_family varchar2
 , p_style varchar2 := 'N'
 , p_fontsize_pt number := null
 , p_output_to_doc boolean := true
 )
 is
 t_dummy pls_integer;
 begin
 t_dummy := set_font( p_family, p_style, p_fontsize_pt, p_output_to_doc );
 end;
 --
 procedure new_page
 is
 begin
 g_pages( g_pages.count() ) := null;
 dbms_lob.createtemporary( g_pages( g_pages.count() - 1 ), true );
 if g_current_font is not null and g_pages.count() > 0
 then
 txt2page( 'BT /F' || g_current_font || ' '
 || to_char_round( g_fonts( g_current_font ).fontsize )
 || ' Tf ET'
 );
 end if;
 g_x := null;
 g_y := null;
 end;
 --
 function pdf_string( p_txt in blob )
 return blob
 is
 t_rv blob;
 t_ind integer;
 type tp_tab_raw is table of raw(1);
 tab_raw tp_tab_raw
 := tp_tab_raw( utl_raw.cast_to_raw( '\' )
 , utl_raw.cast_to_raw( '(' )
 , utl_raw.cast_to_raw( ')' )
 );
 begin
 t_rv := p_txt;
 for i in tab_raw.first .. tab_raw.last
 loop
 t_ind := -1;
 loop
 t_ind := dbms_lob.instr( t_rv
 , tab_raw( i )
 , t_ind + 2
 );
 exit when t_ind <= 0;
 dbms_lob.copy( t_rv
 , t_rv
 , dbms_lob.lobmaxsize
 , t_ind + 1
 , t_ind
 );
 dbms_lob.copy( t_rv
 , utl_raw.cast_to_raw( '\' )
 , 1
 , t_ind
 , 1
 );
 end loop;
 end loop;
 return t_rv;
 end;
 --
 function txt2raw( p_txt varchar2 )
 return raw
 is
 t_rv raw(32767);
 t_unicode pls_integer;
 begin
 if g_current_font is null
 then
 set_font( 'helvetica' );
 end if;
 if g_fonts( g_current_font ).cid
 then
 for i in 1 .. length( p_txt )
 loop
 t_unicode := utl_raw.cast_to_binary_integer( utl_raw.convert( utl_raw.cast_to_raw( substr( p_txt, i, 1 ) )
 , 'AMERICAN_AMERICA.AL16UTF16'
 , sys_context( 'userenv', 'LANGUAGE' ) -- ???? font characterset ?????
 )
 );
 if g_fonts( g_current_font ).flags = 4 -- a symbolic font
 then
 -- assume code 32, space maps to the first code from the font
 t_unicode := g_fonts( g_current_font ).code2glyph.first + t_unicode - 32;
 end if;
 if g_fonts( g_current_font ).code2glyph.exists( t_unicode )
 then
 g_fonts( g_current_font ).used_chars( g_fonts( g_current_font ).code2glyph( t_unicode ) ) := 0;
 t_rv := utl_raw.concat( t_rv
 , utl_raw.cast_to_raw( to_char( g_fonts( g_current_font ).code2glyph( t_unicode ), 'FM0XXX' ) )
 );
 else
 t_rv := utl_raw.concat( t_rv, utl_raw.cast_to_raw( '0000' ) );
 end if;
 end loop;
 t_rv := utl_raw.concat( utl_raw.cast_to_raw( '<' )
 , t_rv
 , utl_raw.cast_to_raw( '>' )
 );
 else
 t_rv := utl_raw.convert( utl_raw.cast_to_raw( p_txt )
 , g_fonts( g_current_font ).charset
 , sys_context( 'userenv', 'LANGUAGE' )
 );
 for i in 1 .. utl_raw.length( t_rv )
 loop
 g_fonts( g_current_font ).used_chars( raw2num( t_rv, i, 1 ) ) := 0;
 end loop;
 t_rv := utl_raw.concat( utl_raw.cast_to_raw( '(' )
 , pdf_string( t_rv )
 , utl_raw.cast_to_raw( ')' )
 );
 end if;
 return t_rv;
 end;
 --
 procedure put_raw( p_x number, p_y number, p_txt raw, p_degrees_rotation number := null )
 is
 c_pi constant number := 3.14159265358979323846264338327950288419716939937510;
 t_tmp varchar2(32767);
 t_sin number;
 t_cos number;
 begin
 t_tmp := to_char_round( p_x ) || ' ' || to_char_round( p_y );
 if p_degrees_rotation is null
 then
 t_tmp := t_tmp || ' Td ';
 else
 t_sin := sin( p_degrees_rotation / 180 * c_pi );
 t_cos := cos( p_degrees_rotation / 180 * c_pi );
 t_tmp := to_char_round( t_cos, 5 ) || ' ' || t_tmp;
 t_tmp := to_char_round( - t_sin, 5 ) || ' ' || t_tmp;
 t_tmp := to_char_round( t_sin, 5 ) || ' ' || t_tmp;
 t_tmp := to_char_round( t_cos, 5 ) || ' ' || t_tmp;
 t_tmp := t_tmp || ' Tm ';
 end if;
 raw2page( utl_raw.concat( utl_raw.cast_to_raw( 'BT ' || t_tmp )
 , p_txt
 , utl_raw.cast_to_raw( ' Tj ET' )
 )
 );
 end;
 --
 procedure put_txt( p_x number, p_y number, p_txt varchar2, p_degrees_rotation number := null )
 is
 begin
 if p_txt is not null
 then
 put_raw( p_x, p_y, txt2raw( p_txt ), p_degrees_rotation );
 end if;
 end;
 --
 function str_len( p_txt in varchar2 )
 return number
 is
 t_width number;
 t_char pls_integer;
 t_rtxt raw(32767);
 t_tmp number;
 t_font tp_font;
 begin
 if p_txt is null
 then
 return 0;
 end if;
 --
 t_width := 0;
 t_font := g_fonts( g_current_font );
 if t_font.cid
 then
 t_rtxt := utl_raw.convert( utl_raw.cast_to_raw( p_txt )
 , 'AMERICAN_AMERICA.AL16UTF16' -- 16 bit font => 2 bytes per char
 , sys_context( 'userenv', 'LANGUAGE' ) -- ???? font characterset ?????
 );
 for i in 1 .. utl_raw.length( t_rtxt ) / 2
 loop
 t_char := to_number( utl_raw.substr( t_rtxt, i * 2 - 1, 2 ), 'xxxx' );
 if t_font.flags = 4 -- a symbolic font
 then
 -- assume code 32, space maps to the first code from the font
 t_char := t_font.code2glyph.first + t_char - 32;
 end if;
 if ( t_font.code2glyph.exists( t_char )
 and t_font.hmetrics.exists( t_font.code2glyph( t_char ) )
 )
 then
 t_tmp := t_font.hmetrics( t_font.code2glyph( t_char ) );
 else
 t_tmp := t_font.hmetrics( t_font.hmetrics.last() );
 end if;
 t_width := t_width + t_tmp;
 end loop;
 t_width := t_width * t_font.unit_norm;
 t_width := t_width * t_font.fontsize / 1000;
 else
 t_rtxt := utl_raw.convert( utl_raw.cast_to_raw( p_txt )
 , t_font.charset -- should be an 8 bit font
 , sys_context( 'userenv', 'LANGUAGE' )
 );
 for i in 1 .. utl_raw.length( t_rtxt )
 loop
 t_char := to_number( utl_raw.substr( t_rtxt, i, 1 ), 'xx' );
 t_width := t_width + t_font.char_width_tab( t_char );
 end loop;
 t_width := t_width * t_font.fontsize / 1000;
 end if;
 return t_width;
 end;
 --
 procedure write
 ( p_txt in varchar2
 , p_x in number := null
 , p_y in number := null
 , p_line_height in number := null
 , p_start in number := null -- left side of the available text box
 , p_width in number := null -- width of the available text box
 , p_alignment in varchar2 := null
 )
 is
 t_line_height number;
 t_x number;
 t_y number;
 t_start number;
 t_width number;
 t_len number;
 t_cnt pls_integer;
 t_ind pls_integer;
 t_alignment varchar2(100);
 begin
 if p_txt is null
 then
 return;
 end if;
 --
 if g_current_font is null
 then
 set_font( 'helvetica' );
 end if;
 --
 t_line_height := nvl( p_line_height, g_fonts( g_current_font ).fontsize );
 if ( t_line_height < g_fonts( g_current_font ).fontsize
 or t_line_height > ( g_settings.page_height - g_settings.margin_top - t_line_height ) / 4
 )
 then
 t_line_height := g_fonts( g_current_font ).fontsize;
 end if;
 t_start := nvl( p_start, g_settings.margin_left );
 if ( t_start < g_settings.margin_left
 or t_start > g_settings.page_width - g_settings.margin_right - g_settings.margin_left
 )
 then
 t_start := g_settings.margin_left;
 end if;
 t_width := nvl( p_width
 , g_settings.page_width - g_settings.margin_right - g_settings.margin_left
 );
 if ( t_width < str_len( ' ' )
 or t_width > g_settings.page_width - g_settings.margin_right - g_settings.margin_left
 )
 then
 t_width := g_settings.page_width - g_settings.margin_right - g_settings.margin_left;
 end if;
 t_x := coalesce( p_x, g_x, g_settings.margin_left );
 t_y := coalesce( p_y
 , g_y
 , g_settings.page_height - g_settings.margin_top - t_line_height
 );
 if t_y < 0
 then
 t_y := coalesce( g_y
 , g_settings.page_height - g_settings.margin_top - t_line_height
 ) - t_line_height;
 end if;
 if t_x > t_start + t_width
 then
 t_x := t_start;
 t_y := t_y - t_line_height;
 elsif t_x < t_start
 then
 t_x := t_start;
 end if;
 if t_y < g_settings.margin_bottom
 then
 new_page;
 t_x := t_start;
 t_y := g_settings.page_height - g_settings.margin_top - t_line_height;
 end if;
 --
 t_ind := instr( p_txt, chr(10) );
 if t_ind > 0
 then
 g_x := t_x;
 g_y := t_y;
 write( rtrim( substr( p_txt, 1, t_ind - 1 ), chr(13) ), t_x, t_y, t_line_height, t_start, t_width, p_alignment );
 t_y := g_y - t_line_height;
 if t_y < g_settings.margin_bottom
 then
 new_page;
 t_y := g_settings.page_height - g_settings.margin_top - t_line_height;
 end if;
 g_x := t_start;
 g_y := t_y;
 write( substr( p_txt, t_ind + 1 ), t_start, t_y, t_line_height, t_start, t_width, p_alignment );
 return;
 end if;
 --
 t_len := str_len( p_txt );
 if t_len <= t_width - t_x + t_start
 then
 t_alignment := lower( substr( p_alignment, 1, 100 ) );
 if instr( t_alignment, 'right' ) > 0 or instr( t_alignment, 'end' ) > 0
 then
 t_x := t_start + t_width - t_len;
 elsif instr( t_alignment, 'center' ) > 0
 then
 t_x := ( t_width + t_x + t_start - t_len ) / 2;
 end if;
 put_txt( t_x, t_y, p_txt );
 g_x := t_x + t_len + str_len( ' ' );
 g_y := t_y;
 return;
 end if;
 --
 t_cnt := 0;
 while ( instr( p_txt, ' ', 1, t_cnt + 1 ) > 0
 and str_len( substr( p_txt, 1, instr( p_txt, ' ', 1, t_cnt + 1 ) - 1 ) ) <= t_width - t_x + t_start
 )
 loop
 t_cnt := t_cnt + 1;
 end loop;
 if t_cnt > 0
 then
 t_ind := instr( p_txt, ' ', 1, t_cnt );
 write( substr( p_txt, 1, t_ind - 1 ), t_x, t_y, t_line_height, t_start, t_width, p_alignment );
 t_y := t_y - t_line_height;
 if t_y < g_settings.margin_bottom
 then
 new_page;
 t_y := g_settings.page_height - g_settings.margin_top - t_line_height;
 end if;
 write( substr( p_txt, t_ind + 1 ), t_start, t_y, t_line_height, t_start, t_width, p_alignment );
 return;
 end if;
 --
 if t_x > t_start and t_len < t_width
 then
 t_y := t_y - t_line_height;
 if t_y < g_settings.margin_bottom
 then
 new_page;
 t_y := g_settings.page_height - g_settings.margin_top - t_line_height;
 end if;
 write( p_txt, t_start, t_y, t_line_height, t_start, t_width, p_alignment );
 else
 if length( p_txt ) = 1
 then
 if t_x > t_start
 then
 t_y := t_y - t_line_height;
 if t_y < g_settings.margin_bottom
 then
 new_page;
 t_y := g_settings.page_height - g_settings.margin_top - t_line_height;
 end if;
 end if;
 write( p_txt, t_x, t_y, t_line_height, t_start, t_len );
 else
 t_ind := 2; -- start with 2 to make sure we get amaller string!
 while str_len( substr( p_txt, 1, t_ind ) ) <= t_width - t_x + t_start
 loop
 t_ind := t_ind + 1;
 end loop;
 write( substr( p_txt, 1, t_ind - 1 ), t_x, t_y, t_line_height, t_start, t_width, p_alignment );
 t_y := t_y - t_line_height;
 if t_y < g_settings.margin_bottom
 then
 new_page;
 t_y := g_settings.page_height - g_settings.margin_top - t_line_height;
 end if;
 write( substr( p_txt, t_ind ), t_start, t_y, t_line_height, t_start, t_width, p_alignment );
 end if;
 end if;
 end;
 --
 function load_ttf_font
 ( p_font blob
 , p_encoding varchar2 := 'WINDOWS-1252'
 , p_embed boolean := false
 , p_compress boolean := true
 , p_offset number := 1
 )
 return pls_integer
 is
 this_font tp_font;
 type tp_font_table is record
 ( offset pls_integer
 , length pls_integer
 );
 type tp_tables is table of tp_font_table index by varchar2(4);
 t_tables tp_tables;
 t_tag varchar2(4);
 t_blob blob;
 t_offset pls_integer;
 nr_hmetrics pls_integer;
 subtype tp_glyphname is varchar2(250);
 type tp_glyphnames is table of tp_glyphname index by pls_integer;
 t_glyphnames tp_glyphnames;
 t_glyph2name tp_pls_tab;
 t_font_ind pls_integer;
 begin
 if dbms_lob.substr( p_font, 4, p_offset ) != hextoraw( '00010000' ) -- OpenType Font
 then
 return null;
 end if;
 for i in 1 .. blob2num( p_font, 2, p_offset + 4 )
 loop
 t_tag :=
 utl_raw.cast_to_varchar2( dbms_lob.substr( p_font, 4, p_offset - 4 + i * 16 ) );
 t_tables( t_tag ).offset := blob2num( p_font, 4, p_offset + 4 + i * 16 ) + 1;
 t_tables( t_tag ).length := blob2num( p_font, 4, p_offset + 8 + i * 16 );
 end loop;
 --
 if ( not t_tables.exists( 'cmap' )
 or not t_tables.exists( 'glyf' )
 or not t_tables.exists( 'head' )
 or not t_tables.exists( 'hhea' )
 or not t_tables.exists( 'hmtx' )
 or not t_tables.exists( 'loca' )
 or not t_tables.exists( 'maxp' )
 or not t_tables.exists( 'name' )
 or not t_tables.exists( 'post' )
 )
 then
 return null;
 end if;
 --
 dbms_lob.createtemporary( t_blob, true );
 dbms_lob.copy( t_blob, p_font, t_tables( 'maxp' ).length, 1, t_tables( 'maxp' ).offset );
 this_font.numGlyphs := blob2num( t_blob, 2, 5 );
 --
 dbms_lob.copy( t_blob, p_font, t_tables( 'cmap' ).length, 1, t_tables( 'cmap' ).offset );
 for i in 0 .. blob2num( t_blob, 2, 3 ) - 1
 loop
 if ( dbms_lob.substr( t_blob, 2, 5 + i * 8 ) = hextoraw( '0003' ) -- Windows
 and dbms_lob.substr( t_blob, 2, 5 + i * 8 + 2 )
 in ( hextoraw( '0000' ) -- Symbol
 , hextoraw( '0001' ) -- Unicode BMP (UCS-2)
 )
 )
 then
 if dbms_lob.substr( t_blob, 2, 5 + i * 8 + 2 ) = hextoraw( '0000' ) -- Symbol
 then
 this_font.flags := 4; -- symbolic
 else
 this_font.flags := 32; -- non-symbolic
 end if;
 t_offset := blob2num( t_blob, 4, 5 + i * 8 + 4 ) + 1;
 if dbms_lob.substr( t_blob, 2, t_offset ) != hextoraw( '0004' )
 then
 return null;
 end if;
 declare
 t_seg_cnt pls_integer;
 t_end_offs pls_integer;
 t_start_offs pls_integer;
 t_idDelta_offs pls_integer;
 t_idRangeOffset_offs pls_integer;
 t_tmp pls_integer;
 t_start pls_integer;
 begin
 t_seg_cnt := blob2num( t_blob, 2, t_offset + 6 ) / 2;
 t_end_offs := t_offset + 14;
 t_start_offs := t_end_offs + t_seg_cnt * 2 + 2;
 t_idDelta_offs := t_start_offs + t_seg_cnt * 2;
 t_idRangeOffset_offs := t_idDelta_offs + t_seg_cnt * 2;
 for seg in 0 .. t_seg_cnt - 1
 loop
 t_tmp := blob2num( t_blob, 2, t_idRangeOffset_offs + seg * 2 );
 if t_tmp = 0
 then
 t_tmp := blob2num( t_blob, 2, t_idDelta_offs + seg * 2 );
 for c in blob2num( t_blob, 2, t_start_offs + seg * 2 )
 .. blob2num( t_blob, 2, t_end_offs + seg * 2 )
 loop
 this_font.code2glyph( c ) := mod( c + t_tmp, 65536 );
 end loop;
 else
 t_start := blob2num( t_blob, 2, t_start_offs + seg * 2 );
 for c in t_start .. blob2num( t_blob, 2, t_end_offs + seg * 2 )
 loop
 this_font.code2glyph( c ) := blob2num( t_blob, 2, t_idRangeOffset_offs + t_tmp + ( seg + c - t_start ) * 2 );
 end loop;
 end if;
 end loop;
 end;
 exit;
 end if;
 end loop;
 --
 t_glyphnames( 0 ) := '.notdef';
 t_glyphnames( 1 ) := '.null';
 t_glyphnames( 2 ) := 'nonmarkingreturn';
 t_glyphnames( 3 ) := 'space';
 t_glyphnames( 4 ) := 'exclam';
 t_glyphnames( 5 ) := 'quotedbl';
 t_glyphnames( 6 ) := 'numbersign';
 t_glyphnames( 7 ) := 'dollar';
 t_glyphnames( 8 ) := 'percent';
 t_glyphnames( 9 ) := 'ampersand';
 t_glyphnames( 10 ) := 'quotesingle';
 t_glyphnames( 11 ) := 'parenleft';
 t_glyphnames( 12 ) := 'parenright';
 t_glyphnames( 13 ) := 'asterisk';
 t_glyphnames( 14 ) := 'plus';
 t_glyphnames( 15 ) := 'comma';
 t_glyphnames( 16 ) := 'hyphen';
 t_glyphnames( 17 ) := 'period';
 t_glyphnames( 18 ) := 'slash';
 t_glyphnames( 19 ) := 'zero';
 t_glyphnames( 20 ) := 'one';
 t_glyphnames( 21 ) := 'two';
 t_glyphnames( 22 ) := 'three';
 t_glyphnames( 23 ) := 'four';
 t_glyphnames( 24 ) := 'five';
 t_glyphnames( 25 ) := 'six';
 t_glyphnames( 26 ) := 'seven';
 t_glyphnames( 27 ) := 'eight';
 t_glyphnames( 28 ) := 'nine';
 t_glyphnames( 29 ) := 'colon';
 t_glyphnames( 30 ) := 'semicolon';
 t_glyphnames( 31 ) := 'less';
 t_glyphnames( 32 ) := 'equal';
 t_glyphnames( 33 ) := 'greater';
 t_glyphnames( 34 ) := 'question';
 t_glyphnames( 35 ) := 'at';
 t_glyphnames( 36 ) := 'A';
 t_glyphnames( 37 ) := 'B';
 t_glyphnames( 38 ) := 'C';
 t_glyphnames( 39 ) := 'D';
 t_glyphnames( 40 ) := 'E';
 t_glyphnames( 41 ) := 'F';
 t_glyphnames( 42 ) := 'G';
 t_glyphnames( 43 ) := 'H';
 t_glyphnames( 44 ) := 'I';
 t_glyphnames( 45 ) := 'J';
 t_glyphnames( 46 ) := 'K';
 t_glyphnames( 47 ) := 'L';
 t_glyphnames( 48 ) := 'M';
 t_glyphnames( 49 ) := 'N';
 t_glyphnames( 50 ) := 'O';
 t_glyphnames( 51 ) := 'P';
 t_glyphnames( 52 ) := 'Q';
 t_glyphnames( 53 ) := 'R';
 t_glyphnames( 54 ) := 'S';
 t_glyphnames( 55 ) := 'T';
 t_glyphnames( 56 ) := 'U';
 t_glyphnames( 57 ) := 'V';
 t_glyphnames( 58 ) := 'W';
 t_glyphnames( 59 ) := 'X';
 t_glyphnames( 60 ) := 'Y';
 t_glyphnames( 61 ) := 'Z';
 t_glyphnames( 62 ) := 'bracketleft';
 t_glyphnames( 63 ) := 'backslash';
 t_glyphnames( 64 ) := 'bracketright';
 t_glyphnames( 65 ) := 'asciicircum';
 t_glyphnames( 66 ) := 'underscore';
 t_glyphnames( 67 ) := 'grave';
 t_glyphnames( 68 ) := 'a';
 t_glyphnames( 69 ) := 'b';
 t_glyphnames( 70 ) := 'c';
 t_glyphnames( 71 ) := 'd';
 t_glyphnames( 72 ) := 'e';
 t_glyphnames( 73 ) := 'f';
 t_glyphnames( 74 ) := 'g';
 t_glyphnames( 75 ) := 'h';
 t_glyphnames( 76 ) := 'i';
 t_glyphnames( 77 ) := 'j';
 t_glyphnames( 78 ) := 'k';
 t_glyphnames( 79 ) := 'l';
 t_glyphnames( 80 ) := 'm';
 t_glyphnames( 81 ) := 'n';
 t_glyphnames( 82 ) := 'o';
 t_glyphnames( 83 ) := 'p';
 t_glyphnames( 84 ) := 'q';
 t_glyphnames( 85 ) := 'r';
 t_glyphnames( 86 ) := 's';
 t_glyphnames( 87 ) := 't';
 t_glyphnames( 88 ) := 'u';
 t_glyphnames( 89 ) := 'v';
 t_glyphnames( 90 ) := 'w';
 t_glyphnames( 91 ) := 'x';
 t_glyphnames( 92 ) := 'y';
 t_glyphnames( 93 ) := 'z';
 t_glyphnames( 94 ) := 'braceleft';
 t_glyphnames( 95 ) := 'bar';
 t_glyphnames( 96 ) := 'braceright';
 t_glyphnames( 97 ) := 'asciitilde';
 t_glyphnames( 98 ) := 'Adieresis';
 t_glyphnames( 99 ) := 'Aring';
 t_glyphnames( 100 ) := 'Ccedilla';
 t_glyphnames( 101 ) := 'Eacute';
 t_glyphnames( 102 ) := 'Ntilde';
 t_glyphnames( 103 ) := 'Odieresis';
 t_glyphnames( 104 ) := 'Udieresis';
 t_glyphnames( 105 ) := 'aacute';
 t_glyphnames( 106 ) := 'agrave';
 t_glyphnames( 107 ) := 'acircumflex';
 t_glyphnames( 108 ) := 'adieresis';
 t_glyphnames( 109 ) := 'atilde';
 t_glyphnames( 110 ) := 'aring';
 t_glyphnames( 111 ) := 'ccedilla';
 t_glyphnames( 112 ) := 'eacute';
 t_glyphnames( 113 ) := 'egrave';
 t_glyphnames( 114 ) := 'ecircumflex';
 t_glyphnames( 115 ) := 'edieresis';
 t_glyphnames( 116 ) := 'iacute';
 t_glyphnames( 117 ) := 'igrave';
 t_glyphnames( 118 ) := 'icircumflex';
 t_glyphnames( 119 ) := 'idieresis';
 t_glyphnames( 120 ) := 'ntilde';
 t_glyphnames( 121 ) := 'oacute';
 t_glyphnames( 122 ) := 'ograve';
 t_glyphnames( 123 ) := 'ocircumflex';
 t_glyphnames( 124 ) := 'odieresis';
 t_glyphnames( 125 ) := 'otilde';
 t_glyphnames( 126 ) := 'uacute';
 t_glyphnames( 127 ) := 'ugrave';
 t_glyphnames( 128 ) := 'ucircumflex';
 t_glyphnames( 129 ) := 'udieresis';
 t_glyphnames( 130 ) := 'dagger';
 t_glyphnames( 131 ) := 'degree';
 t_glyphnames( 132 ) := 'cent';
 t_glyphnames( 133 ) := 'sterling';
 t_glyphnames( 134 ) := 'section';
 t_glyphnames( 135 ) := 'bullet';
 t_glyphnames( 136 ) := 'paragraph';
 t_glyphnames( 137 ) := 'germandbls';
 t_glyphnames( 138 ) := 'registered';
 t_glyphnames( 139 ) := 'copyright';
 t_glyphnames( 140 ) := 'trademark';
 t_glyphnames( 141 ) := 'acute';
 t_glyphnames( 142 ) := 'dieresis';
 t_glyphnames( 143 ) := 'notequal';
 t_glyphnames( 144 ) := 'AE';
 t_glyphnames( 145 ) := 'Oslash';
 t_glyphnames( 146 ) := 'infinity';
 t_glyphnames( 147 ) := 'plusminus';
 t_glyphnames( 148 ) := 'lessequal';
 t_glyphnames( 149 ) := 'greaterequal';
 t_glyphnames( 150 ) := 'yen';
 t_glyphnames( 151 ) := 'mu';
 t_glyphnames( 152 ) := 'partialdiff';
 t_glyphnames( 153 ) := 'summation';
 t_glyphnames( 154 ) := 'product';
 t_glyphnames( 155 ) := 'pi';
 t_glyphnames( 156 ) := 'integral';
 t_glyphnames( 157 ) := 'ordfeminine';
 t_glyphnames( 158 ) := 'ordmasculine';
 t_glyphnames( 159 ) := 'Omega';
 t_glyphnames( 160 ) := 'ae';
 t_glyphnames( 161 ) := 'oslash';
 t_glyphnames( 162 ) := 'questiondown';
 t_glyphnames( 163 ) := 'exclamdown';
 t_glyphnames( 164 ) := 'logicalnot';
 t_glyphnames( 165 ) := 'radical';
 t_glyphnames( 166 ) := 'florin';
 t_glyphnames( 167 ) := 'approxequal';
 t_glyphnames( 168 ) := 'Delta';
 t_glyphnames( 169 ) := 'guillemotleft';
 t_glyphnames( 170 ) := 'guillemotright';
 t_glyphnames( 171 ) := 'ellipsis';
 t_glyphnames( 172 ) := 'nonbreakingspace';
 t_glyphnames( 173 ) := 'Agrave';
 t_glyphnames( 174 ) := 'Atilde';
 t_glyphnames( 175 ) := 'Otilde';
 t_glyphnames( 176 ) := 'OE';
 t_glyphnames( 177 ) := 'oe';
 t_glyphnames( 178 ) := 'endash';
 t_glyphnames( 179 ) := 'emdash';
 t_glyphnames( 180 ) := 'quotedblleft';
 t_glyphnames( 181 ) := 'quotedblright';
 t_glyphnames( 182 ) := 'quoteleft';
 t_glyphnames( 183 ) := 'quoteright';
 t_glyphnames( 184 ) := 'divide';
 t_glyphnames( 185 ) := 'lozenge';
 t_glyphnames( 186 ) := 'ydieresis';
 t_glyphnames( 187 ) := 'Ydieresis';
 t_glyphnames( 188 ) := 'fraction';
 t_glyphnames( 189 ) := 'currency';
 t_glyphnames( 190 ) := 'guilsinglleft';
 t_glyphnames( 191 ) := 'guilsinglright';
 t_glyphnames( 192 ) := 'fi';
 t_glyphnames( 193 ) := 'fl';
 t_glyphnames( 194 ) := 'daggerdbl';
 t_glyphnames( 195 ) := 'periodcentered';
 t_glyphnames( 196 ) := 'quotesinglbase';
 t_glyphnames( 197 ) := 'quotedblbase';
 t_glyphnames( 198 ) := 'perthousand';
 t_glyphnames( 199 ) := 'Acircumflex';
 t_glyphnames( 200 ) := 'Ecircumflex';
 t_glyphnames( 201 ) := 'Aacute';
 t_glyphnames( 202 ) := 'Edieresis';
 t_glyphnames( 203 ) := 'Egrave';
 t_glyphnames( 204 ) := 'Iacute';
 t_glyphnames( 205 ) := 'Icircumflex';
 t_glyphnames( 206 ) := 'Idieresis';
 t_glyphnames( 207 ) := 'Igrave';
 t_glyphnames( 208 ) := 'Oacute';
 t_glyphnames( 209 ) := 'Ocircumflex';
 t_glyphnames( 210 ) := 'apple';
 t_glyphnames( 211 ) := 'Ograve';
 t_glyphnames( 212 ) := 'Uacute';
 t_glyphnames( 213 ) := 'Ucircumflex';
 t_glyphnames( 214 ) := 'Ugrave';
 t_glyphnames( 215 ) := 'dotlessi';
 t_glyphnames( 216 ) := 'circumflex';
 t_glyphnames( 217 ) := 'tilde';
 t_glyphnames( 218 ) := 'macron';
 t_glyphnames( 219 ) := 'breve';
 t_glyphnames( 220 ) := 'dotaccent';
 t_glyphnames( 221 ) := 'ring';
 t_glyphnames( 222 ) := 'cedilla';
 t_glyphnames( 223 ) := 'hungarumlaut';
 t_glyphnames( 224 ) := 'ogonek';
 t_glyphnames( 225 ) := 'caron';
 t_glyphnames( 226 ) := 'Lslash';
 t_glyphnames( 227 ) := 'lslash';
 t_glyphnames( 228 ) := 'Scaron';
 t_glyphnames( 229 ) := 'scaron';
 t_glyphnames( 230 ) := 'Zcaron';
 t_glyphnames( 231 ) := 'zcaron';
 t_glyphnames( 232 ) := 'brokenbar';
 t_glyphnames( 233 ) := 'Eth';
 t_glyphnames( 234 ) := 'eth';
 t_glyphnames( 235 ) := 'Yacute';
 t_glyphnames( 236 ) := 'yacute';
 t_glyphnames( 237 ) := 'Thorn';
 t_glyphnames( 238 ) := 'thorn';
 t_glyphnames( 239 ) := 'minus';
 t_glyphnames( 240 ) := 'multiply';
 t_glyphnames( 241 ) := 'onesuperior';
 t_glyphnames( 242 ) := 'twosuperior';
 t_glyphnames( 243 ) := 'threesuperior';
 t_glyphnames( 244 ) := 'onehalf';
 t_glyphnames( 245 ) := 'onequarter';
 t_glyphnames( 246 ) := 'threequarters';
 t_glyphnames( 247 ) := 'franc';
 t_glyphnames( 248 ) := 'Gbreve';
 t_glyphnames( 249 ) := 'gbreve';
 t_glyphnames( 250 ) := 'Idotaccent';
 t_glyphnames( 251 ) := 'Scedilla';
 t_glyphnames( 252 ) := 'scedilla';
 t_glyphnames( 253 ) := 'Cacute';
 t_glyphnames( 254 ) := 'cacute';
 t_glyphnames( 255 ) := 'Ccaron';
 t_glyphnames( 256 ) := 'ccaron';
 t_glyphnames( 257 ) := 'dcroat';
 --
 dbms_lob.copy( t_blob, p_font, t_tables( 'post' ).length, 1, t_tables( 'post' ).offset );
 this_font.italic_angle := to_short( dbms_lob.substr( t_blob, 2, 5 ) )
 + to_short( dbms_lob.substr( t_blob, 2, 7 ) ) / 65536;
 case rawtohex( dbms_lob.substr( t_blob, 4, 1 ) )
 when '00010000'
 then
 for g in 0 .. 257
 loop
 t_glyph2name( g ) := g;
 end loop;
 when '00020000'
 then
 t_offset := blob2num( t_blob, 2, 33 ) * 2 + 35;
 while nvl( blob2num( t_blob, 1, t_offset ), 0 ) > 0
 loop
 t_glyphnames( t_glyphnames.count ) := utl_raw.cast_to_varchar2( dbms_lob.substr( t_blob, blob2num( t_blob, 1, t_offset ), t_offset + 1 ) );
 t_offset := t_offset + blob2num( t_blob, 1, t_offset ) + 1;
 end loop;
 for g in 0 .. blob2num( t_blob, 2, 33 ) - 1
 loop
 t_glyph2name( g ) := blob2num( t_blob, 2, 35 + 2 * g );
 end loop;
 when '00025000'
 then
 for g in 0 .. blob2num( t_blob, 2, 33 ) - 1
 loop
 t_offset := blob2num( t_blob, 1, 35 + g );
 if t_offset > 127
 then
 t_glyph2name( g ) := g - t_offset;
 else
 t_glyph2name( g ) := g + t_offset;
 end if;
 end loop;
 when '00030000'
 then
 t_glyphnames.delete;
 else
 dbms_output.put_line( 'no post ' || dbms_lob.substr( t_blob, 4, 1 ) );
 end case;
 --
 dbms_lob.copy( t_blob, p_font, t_tables( 'head' ).length, 1, t_tables( 'head' ).offset );
 if dbms_lob.substr( t_blob, 4, 13 ) = hextoraw( '5F0F3CF5' ) -- magic
 then
 declare
 t_tmp pls_integer := blob2num( t_blob, 2, 45 );
 begin
 if bitand( t_tmp, 1 ) = 1
 then
 this_font.style := 'B';
 end if;
 if bitand( t_tmp, 2 ) = 2
 then
 this_font.style := this_font.style || 'I';
 this_font.flags := this_font.flags + 64;
 end if;
 this_font.style := nvl( this_font.style, 'N' );
 this_font.unit_norm := 1000 / blob2num( t_blob, 2, 19 );
 this_font.bb_xmin := to_short( dbms_lob.substr( t_blob, 2, 37 ), this_font.unit_norm );
 this_font.bb_ymin := to_short( dbms_lob.substr( t_blob, 2, 39 ), this_font.unit_norm );
 this_font.bb_xmax := to_short( dbms_lob.substr( t_blob, 2, 41 ), this_font.unit_norm );
 this_font.bb_ymax := to_short( dbms_lob.substr( t_blob, 2, 43 ), this_font.unit_norm );
 this_font.indexToLocFormat := blob2num( t_blob, 2, 51 ); -- 0 for short offsets, 1 for long
 end;
 end if;
 --
 dbms_lob.copy( t_blob, p_font, t_tables( 'hhea' ).length, 1, t_tables( 'hhea' ).offset );
 if dbms_lob.substr( t_blob, 4, 1 ) = hextoraw( '00010000' ) -- version 1.0
 then
 this_font.ascent := to_short( dbms_lob.substr( t_blob, 2, 5 ), this_font.unit_norm );
 this_font.descent := to_short( dbms_lob.substr( t_blob, 2, 7 ), this_font.unit_norm );
 this_font.capheight := this_font.ascent;
 nr_hmetrics := blob2num( t_blob, 2, 35 );
 end if;
 --
 dbms_lob.copy( t_blob, p_font, t_tables( 'hmtx' ).length, 1, t_tables( 'hmtx' ).offset );
 for j in 0 .. nr_hmetrics - 1
 loop
 this_font.hmetrics( j ) := blob2num( t_blob, 2, 1 + 4 * j );
 end loop;
 --
 dbms_lob.copy( t_blob, p_font, t_tables( 'name' ).length, 1, t_tables( 'name' ).offset );
 if dbms_lob.substr( t_blob, 2, 1 ) = hextoraw( '0000' ) -- format 0
 then
 t_offset := blob2num( t_blob, 2, 5 ) + 1;
 for j in 0 .. blob2num( t_blob, 2, 3 ) - 1
 loop
 if ( dbms_lob.substr( t_blob, 2, 7 + j * 12 ) = hextoraw( '0003' ) -- Windows
 and dbms_lob.substr( t_blob, 2, 11 + j * 12 ) = hextoraw( '0409' ) -- English United States
 )
 then
 case rawtohex( dbms_lob.substr( t_blob, 2, 13 + j * 12 ) )
 when '0001'
 then
 this_font.family := utl_i18n.raw_to_char( dbms_lob.substr( t_blob, blob2num( t_blob, 2, 15 + j * 12 ), t_offset + blob2num( t_blob, 2, 17 + j * 12 ) ), 'AL16UTF16' );
 when '0006'
 then
 this_font.name := utl_i18n.raw_to_char( dbms_lob.substr( t_blob, blob2num( t_blob, 2, 15 + j * 12 ), t_offset + blob2num( t_blob, 2, 17 + j * 12 ) ), 'AL16UTF16' );
 else
 null;
 end case;
 end if;
 end loop;
 end if;
 --
 if this_font.italic_angle != 0
 then
 this_font.flags := this_font.flags + 64;
 end if;
 this_font.subtype := 'TrueType';
 this_font.stemv := 50;
 this_font.family := lower( this_font.family );
 this_font.encoding := utl_i18n.map_charset( p_encoding
 , utl_i18n.generic_context
 , utl_i18n.iana_to_oracle
 );
 this_font.encoding := nvl( this_font.encoding, upper( p_encoding ) );
 this_font.charset := sys_context( 'userenv', 'LANGUAGE' );
 this_font.charset := substr( this_font.charset
 , 1
 , instr( this_font.charset, '.' )
 ) || this_font.encoding;
 this_font.cid := upper( p_encoding ) in ( 'CID', 'AL16UTF16', 'UTF', 'UNICODE' );
 this_font.fontname := this_font.name;
 this_font.compress_font := p_compress;
 --
 if ( p_embed or this_font.cid ) and t_tables.exists( 'OS/2' )
 then
 dbms_lob.copy( t_blob, p_font, t_tables( 'OS/2' ).length, 1, t_tables( 'OS/2' ).offset );
 if blob2num( t_blob, 2, 9 ) != 2
 then
 this_font.fontfile2 := p_font;
 this_font.ttf_offset := p_offset;
 this_font.name := dbms_random.string( 'u', 6 ) || '+' || this_font.name;
 --
 t_blob := dbms_lob.substr( p_font, t_tables( 'loca' ).length, t_tables( 'loca' ).offset );
 declare
 t_size pls_integer := 2 + this_font.indexToLocFormat * 2; -- 0 for short offsets, 1 for long
 begin
 for i in 0 .. this_font.numGlyphs
 loop
 this_font.loca( i ) := blob2num( t_blob, t_size, 1 + i * t_size );
 end loop;
 end;
 end if;
 end if;
 --
 if not this_font.cid
 then
 if this_font.flags = 4 -- a symbolic font
 then
 declare
 t_real pls_integer;
 begin
 for t_code in 32 .. 255
 loop
 t_real := this_font.code2glyph.first + t_code - 32; -- assume code 32, space maps to the first code from the font
 if this_font.code2glyph.exists( t_real )
 then
 this_font.first_char := least( nvl( this_font.first_char, 255 ), t_code );
 this_font.last_char := t_code;
 if this_font.hmetrics.exists( this_font.code2glyph( t_real ) )
 then
 this_font.char_width_tab( t_code ) := trunc( this_font.hmetrics( this_font.code2glyph( t_real ) ) * this_font.unit_norm );
 else
 this_font.char_width_tab( t_code ) := trunc( this_font.hmetrics( this_font.hmetrics.last() ) * this_font.unit_norm );
 end if;
 else
 this_font.char_width_tab( t_code ) := trunc( this_font.hmetrics( 0 ) * this_font.unit_norm );
 end if;
 end loop;
 end;
 else
 declare
 t_unicode pls_integer;
 t_prv_diff pls_integer;
 t_utf16_charset varchar2(1000);
 t_winansi_charset varchar2(1000);
 t_glyphname tp_glyphname;
 begin
 t_prv_diff := -1;
 t_utf16_charset := substr( this_font.charset, 1, instr( this_font.charset, '.' ) ) || 'AL16UTF16';
 t_winansi_charset := substr( this_font.charset, 1, instr( this_font.charset, '.' ) ) || 'WE8MSWIN1252';
 for t_code in 32 .. 255
 loop
 t_unicode := utl_raw.cast_to_binary_integer( utl_raw.convert( hextoraw( to_char( t_code, 'fm0x' ) )
 , t_utf16_charset
 , this_font.charset
 )
 );
 t_glyphname := '';
 this_font.char_width_tab( t_code ) := trunc( this_font.hmetrics( this_font.hmetrics.last() ) * this_font.unit_norm );
 if this_font.code2glyph.exists( t_unicode )
 then
 this_font.first_char := least( nvl( this_font.first_char, 255 ), t_code );
 this_font.last_char := t_code;
 if this_font.hmetrics.exists( this_font.code2glyph( t_unicode ) )
 then
 this_font.char_width_tab( t_code ) := trunc( this_font.hmetrics( this_font.code2glyph( t_unicode ) ) * this_font.unit_norm );
 end if;
 if t_glyph2name.exists( this_font.code2glyph( t_unicode ) )
 then
 if t_glyphnames.exists( t_glyph2name( this_font.code2glyph( t_unicode ) ) )
 then
 t_glyphname := t_glyphnames( t_glyph2name( this_font.code2glyph( t_unicode ) ) );
 end if;
 end if;
 end if;
 --
 if ( t_glyphname is not null
 and t_unicode != utl_raw.cast_to_binary_integer( utl_raw.convert( hextoraw( to_char( t_code, 'fm0x' ) )
 , t_winansi_charset
 , this_font.charset
 )
 )
 )
 then
 this_font.diff := this_font.diff || case when t_prv_diff != t_code - 1 then ' ' || t_code end || ' /' || t_glyphname;
 t_prv_diff := t_code;
 end if;
 end loop;
 end;
 if this_font.diff is not null
 then
 this_font.diff := '/Differences [' || this_font.diff || ']';
 end if;
 end if;
 end if;
 --
 t_font_ind := g_fonts.count( ) + 1;
 g_fonts( t_font_ind ) := this_font;
 /*
 --
 dbms_output.put_line( this_font.fontname || ' ' || this_font.family || ' ' || this_font.style
 || ' ' || this_font.flags
 || ' ' || this_font.code2glyph.first
 || ' ' || this_font.code2glyph.prior( this_font.code2glyph.last )
 || ' ' || this_font.code2glyph.last
 || ' nr glyphs: ' || this_font.numGlyphs
 ); */
 --
 return t_font_ind;
 end;
 --
 procedure load_ttf_font
 ( p_font blob
 , p_encoding varchar2 := 'WINDOWS-1252'
 , p_embed boolean := false
 , p_compress boolean := true
 , p_offset number := 1
 )
 is
 t_tmp pls_integer;
 begin
 t_tmp := load_ttf_font( p_font, p_encoding, p_embed, p_compress );
 end;
 --
 function load_ttf_font
 ( p_dir varchar2 := 'MY_FONTS'
 , p_filename varchar2 := 'BAUHS93.TTF'
 , p_encoding varchar2 := 'WINDOWS-1252'
 , p_embed boolean := false
 , p_compress boolean := true
 )
 return pls_integer
 is
 begin
 return load_ttf_font( file2blob( p_dir, p_filename ), p_encoding, p_embed, p_compress );
 end;
 --
 procedure load_ttf_font
 ( p_dir varchar2 := 'MY_FONTS'
 , p_filename varchar2 := 'BAUHS93.TTF'
 , p_encoding varchar2 := 'WINDOWS-1252'
 , p_embed boolean := false
 , p_compress boolean := true
 )
 is
 begin
 load_ttf_font( file2blob( p_dir, p_filename ), p_encoding, p_embed, p_compress );
 end;
 --
 procedure load_ttc_fonts
 ( p_ttc blob
 , p_encoding varchar2 := 'WINDOWS-1252'
 , p_embed boolean := false
 , p_compress boolean := true
 )
 is
 type tp_font_table is record
 ( offset pls_integer
 , length pls_integer
 );
 type tp_tables is table of tp_font_table index by varchar2(4);
 t_tables tp_tables;
 t_tag varchar2(4);
 t_blob blob;
 t_offset pls_integer;
 t_font_ind pls_integer;
 begin
 if utl_raw.cast_to_varchar2( dbms_lob.substr( p_ttc, 4, 1 ) ) != 'ttcf'
 then
 return;
 end if;
 for f in 0 .. blob2num( p_ttc, 4, 9 ) - 1
 loop
 t_font_ind := load_ttf_font( p_ttc, p_encoding, p_embed, p_compress, blob2num( p_ttc, 4, 13 + f * 4 ) + 1 );
 dbms_output.put_line( t_font_ind || ' ' || g_fonts( t_font_ind ).fontname || ' ' || g_fonts( t_font_ind ).family || ' ' || g_fonts( t_font_ind ).style );
 end loop;
 end;
 --
 procedure load_ttc_fonts
 ( p_dir varchar2 := 'MY_FONTS'
 , p_filename varchar2 := 'CAMBRIA.TTC'
 , p_encoding varchar2 := 'WINDOWS-1252'
 , p_embed boolean := false
 , p_compress boolean := true
 )
 is
 begin
 load_ttc_fonts( file2blob( p_dir, p_filename ), p_encoding, p_embed, p_compress );
 end;
 --
 function rgb( p_hex_rgb varchar2 )
 return varchar2
 is
 begin
 return to_char_round( nvl( to_number( substr( ltrim( p_hex_rgb, '#' )
 , 1, 2 )
 , 'xx' ) / 255
 , 0 )
 , 5 ) || ' '
 || to_char_round( nvl( to_number( substr( ltrim( p_hex_rgb, '#' )
 , 3, 2 )
 , 'xx' ) / 255
 , 0 )
 , 5 ) || ' '
 || to_char_round( nvl( to_number( substr( ltrim( p_hex_rgb, '#' )
 , 5, 2 )
 , 'xx' ) / 255
 , 0 )
 , 5 ) || ' ';
 end;
 --
 procedure set_color( p_rgb varchar2 := '000000', p_backgr boolean )
 is
 begin
 txt2page( rgb( p_rgb ) || case when p_backgr then 'RG' else 'rg' end );
 end;
 --
 procedure set_color( p_rgb varchar2 := '000000' )
 is
 begin
 set_color( p_rgb, false );
 end;
 --
 procedure set_color
 ( p_red number := 0
 , p_green number := 0
 , p_blue number := 0
 )
 is
 begin
 if ( p_red between 0 and 255
 and p_blue between 0 and 255
 and p_green between 0 and 255
 )
 then
 set_color( to_char( p_red, 'fm0x' )
 || to_char( p_green, 'fm0x' )
 || to_char( p_blue, 'fm0x' )
 , false
 );
 end if;
 end;
 --
 procedure set_bk_color( p_rgb varchar2 := 'ffffff' )
 is
 begin
 set_color( p_rgb, true );
 end;
 --
 procedure set_bk_color
 ( p_red number := 0
 , p_green number := 0
 , p_blue number := 0
 )
 is
 begin
 if ( p_red between 0 and 255
 and p_blue between 0 and 255
 and p_green between 0 and 255
 )
 then
 set_color( to_char( p_red, 'fm0x' )
 || to_char( p_green, 'fm0x' )
 || to_char( p_blue, 'fm0x' )
 , true
 );
 end if;
 end;
 --
 procedure horizontal_line
 ( p_x number
 , p_y number
 , p_width number
 , p_line_width number := 0.5
 , p_line_color varchar2 := '000000'
 )
 is
 t_use_color boolean;
 begin
 txt2page( 'q ' || to_char_round( p_line_width, 5 ) || ' w' );
 t_use_color := substr( p_line_color
 , -6
 ) != '000000';
 if t_use_color
 then
 set_color( p_line_color );
 set_bk_color( p_line_color );
 else
 txt2page( '0 g' );
 end if;
 txt2page( to_char_round( p_x, 5 ) || ' '
 || to_char_round( p_y, 5 ) || ' m '
 || to_char_round( p_x + p_width, 5 ) || ' '
 || to_char_round( p_y, 5 ) || ' l b'
 );
 txt2page( 'Q' );
 end;
 --
 procedure vertical_line
 ( p_x number
 , p_y number
 , p_height number
 , p_line_width number := 0.5
 , p_line_color varchar2 := '000000'
 )
 is
 t_use_color boolean;
 begin
 txt2page( 'q ' || to_char_round( p_line_width, 5 ) || ' w' );
 t_use_color := substr( p_line_color
 , -6
 ) != '000000';
 if t_use_color
 then
 set_color( p_line_color );
 set_bk_color( p_line_color );
 else
 txt2page( '0 g' );
 end if;
 txt2page( to_char_round( p_x, 5 ) || ' '
 || to_char_round( p_y, 5 ) || ' m '
 || to_char_round( p_x, 5 ) || ' '
 || to_char_round( p_y + p_height, 5 ) || ' l b'
 );
 txt2page( 'Q' );
 end;
 --
 procedure rect
 ( p_x number
 , p_y number
 , p_width number
 , p_height number
 , p_line_color varchar2 := null
 , p_fill_color varchar2 := null
 , p_line_width number := 0.5
 )
 is
 begin
 txt2page( 'q' );
 if substr( p_line_color, -6 ) != substr( p_fill_color, -6 )
 then
 txt2page( to_char_round( p_line_width, 5 ) || ' w' );
 end if;
 if substr( p_line_color, -6 ) != '000000'
 then
 set_bk_color( p_line_color );
 else
 txt2page( '0 g' );
 end if;
 if p_fill_color is not null
 then
 set_color( p_fill_color );
 end if;
 txt2page( to_char_round( p_x, 5 ) || ' ' || to_char_round( p_y, 5 ) || ' '
 || to_char_round( p_width, 5 ) || ' ' || to_char_round( p_height, 5 ) || ' re '
 || case
 when p_fill_color is null
 then 'S'
 else case when p_line_color is null then 'f' else 'b' end
 end
 );
 txt2page( 'Q' );
 end;
 --
 function get( p_what pls_integer )
 return number
 is
 begin
 return case p_what
 when c_get_page_width then g_settings.page_width
 when c_get_page_height then g_settings.page_height
 when c_get_margin_top then g_settings.margin_top
 when c_get_margin_right then g_settings.margin_right
 when c_get_margin_bottom then g_settings.margin_bottom
 when c_get_margin_left then g_settings.margin_left
 when c_get_x then g_x
 when c_get_y then g_y
 when c_get_fontsize then g_fonts( g_current_font ).fontsize
 when c_get_current_font then g_current_font
 end;
 end;
 --
 function parse_jpg( p_img_blob blob )
 return tp_img
 is
 buf raw(4);
 t_img tp_img;
 t_ind integer;
 begin
 if ( dbms_lob.substr( p_img_blob, 2, 1 ) != hextoraw( 'FFD8' ) -- SOI Start of Image
 or dbms_lob.substr( p_img_blob, 2, dbms_lob.getlength( p_img_blob ) - 1 ) != hextoraw( 'FFD9' ) -- EOI End of Image
 )
 then -- this is not a jpg I can handle
 return null;
 end if;
 --
 t_img.pixels := p_img_blob;
 t_img.type := 'jpg';
 if dbms_lob.substr( t_img.pixels, 2, 3 ) in ( hextoraw( 'FFE0' ) -- a APP0 jpg
 , hextoraw( 'FFE1' ) -- a APP1 jpg
 )
 then
 t_img.color_res := 8;
 t_img.height := 1;
 t_img.width := 1;
 --
 t_ind := 3;
 t_ind := t_ind + 2 + blob2num( t_img.pixels, 2, t_ind + 2 );
 loop
 buf := dbms_lob.substr( t_img.pixels, 2, t_ind );
 exit when buf = hextoraw( 'FFDA' ); -- SOS Start of Scan
 exit when buf = hextoraw( 'FFD9' ); -- EOI End Of Image
 exit when substr( rawtohex( buf ), 1, 2 ) != 'FF';
 if rawtohex( buf ) in ( 'FFD0' -- RSTn
 , 'FFD1', 'FFD2', 'FFD3', 'FFD4', 'FFD5', 'FFD6', 'FFD7', 'FF01' -- TEM
 )
 then
 t_ind := t_ind + 2;
 else
 if buf = hextoraw( 'FFC0' ) -- SOF0 (Start Of Frame 0) marker
 then
 t_img.color_res := blob2num( t_img.pixels, 1, t_ind + 4 );
 t_img.height := blob2num( t_img.pixels, 2, t_ind + 5 );
 t_img.width := blob2num( t_img.pixels, 2, t_ind + 7 );
 end if;
 t_ind := t_ind + 2 + blob2num( t_img.pixels, 2, t_ind + 2 );
 end if;
 end loop;
 end if;
 --
 return t_img;
 end;
 --
 function parse_png( p_img_blob blob )
 return tp_img
 is
 t_img tp_img;
 buf raw(32767);
 len integer;
 ind integer;
 color_type pls_integer;
 begin
 if rawtohex( dbms_lob.substr( p_img_blob, 8, 1 ) ) != '89504E470D0A1A0A' -- not the right signature
 then
 return null;
 end if;
 dbms_lob.createtemporary( t_img.pixels, true );
 ind := 9;
 loop
 len := blob2num( p_img_blob, 4, ind ); -- length
 exit when len is null or ind > dbms_lob.getlength( p_img_blob );
 case utl_raw.cast_to_varchar2( dbms_lob.substr( p_img_blob, 4, ind + 4 ) ) -- Chunk type
 when 'IHDR'
 then
 t_img.width := blob2num( p_img_blob, 4, ind + 8 );
 t_img.height := blob2num( p_img_blob, 4, ind + 12 );
 t_img.color_res := blob2num( p_img_blob, 1, ind + 16 );
 color_type := blob2num( p_img_blob, 1, ind + 17 );
 t_img.greyscale := color_type in ( 0, 4 );
 when 'PLTE'
 then
 t_img.color_tab := dbms_lob.substr( p_img_blob, len, ind + 8 );
 when 'IDAT'
 then
 dbms_lob.copy( t_img.pixels, p_img_blob, len, dbms_lob.getlength( t_img.pixels ) + 1, ind + 8 );
 when 'IEND'
 then
 exit;
 else
 null;
 end case;
 ind := ind + 4 + 4 + len + 4; -- Length + Chunk type + Chunk data + CRC
 end loop;
 --
 t_img.type := 'png';
 t_img.nr_colors := case color_type
 when 0 then 1
 when 2 then 3
 when 3 then 1
 when 4 then 2
 else 4
 end;
 --
 return t_img;
 end;
 --
 function lzw_decompress
 ( p_blob blob
 , p_bits pls_integer
 )
 return blob
 is
 powers tp_pls_tab;
 --
 g_lzw_ind pls_integer;
 g_lzw_bits pls_integer;
 g_lzw_buffer pls_integer;
 g_lzw_bits_used pls_integer;
 --
 type tp_lzw_dict is table of raw(1000) index by pls_integer;
 t_lzw_dict tp_lzw_dict;
 t_clr_code pls_integer;
 t_nxt_code pls_integer;
 t_new_code pls_integer;
 t_old_code pls_integer;
 t_blob blob;
 --
 function get_lzw_code
 return pls_integer
 is
 t_rv pls_integer;
 begin
 while g_lzw_bits_used < g_lzw_bits
 loop
 g_lzw_ind := g_lzw_ind + 1;
 g_lzw_buffer := blob2num( p_blob, 1, g_lzw_ind ) * powers( g_lzw_bits_used ) + g_lzw_buffer;
 g_lzw_bits_used := g_lzw_bits_used + 8;
 end loop;
 t_rv := bitand( g_lzw_buffer, powers( g_lzw_bits ) - 1 );
 g_lzw_bits_used := g_lzw_bits_used - g_lzw_bits;
 g_lzw_buffer := trunc( g_lzw_buffer / powers( g_lzw_bits ) );
 return t_rv;
 end;
 --
 begin
 for i in 0 .. 30
 loop
 powers( i ) := power( 2, i );
 end loop;
 --
 t_clr_code := powers( p_bits - 1 );
 t_nxt_code := t_clr_code + 2;
 for i in 0 .. least( t_clr_code - 1, 255 )
 loop
 t_lzw_dict( i ) := hextoraw( to_char( i, 'fm0X' ) );
 end loop;
 dbms_lob.createtemporary( t_blob, true );
 g_lzw_ind := 0;
 g_lzw_bits := p_bits;
 g_lzw_buffer := 0;
 g_lzw_bits_used := 0;
 --
 t_old_code := null;
 t_new_code := get_lzw_code( );
 loop
 case nvl( t_new_code, t_clr_code + 1 )
 when t_clr_code + 1
 then
 exit;
 when t_clr_code
 then
 t_new_code := null;
 g_lzw_bits := p_bits;
 t_nxt_code := t_clr_code + 2;
 else
 if t_new_code = t_nxt_code
 then
 t_lzw_dict( t_nxt_code ) :=
 utl_raw.concat( t_lzw_dict( t_old_code )
 , utl_raw.substr( t_lzw_dict( t_old_code ), 1, 1 )
 );
 dbms_lob.append( t_blob, t_lzw_dict( t_nxt_code ) );
 t_nxt_code := t_nxt_code + 1;
 elsif t_new_code > t_nxt_code
 then
 exit;
 else
 dbms_lob.append( t_blob, t_lzw_dict( t_new_code ) );
 if t_old_code is not null
 then
 t_lzw_dict( t_nxt_code ) := utl_raw.concat( t_lzw_dict( t_old_code )
 , utl_raw.substr( t_lzw_dict( t_new_code ), 1, 1 )
 );
 t_nxt_code := t_nxt_code + 1;
 end if;
 end if;
 if bitand( t_nxt_code, powers( g_lzw_bits ) - 1 ) = 0
 and g_lzw_bits < 12
 then
 g_lzw_bits := g_lzw_bits + 1;
 end if;
 end case;
 t_old_code := t_new_code;
 t_new_code := get_lzw_code( );
 end loop;
 t_lzw_dict.delete;
 --
 return t_blob;
 end;
 --
 function parse_gif( p_img_blob blob )
 return tp_img
 is
 img tp_img;
 buf raw(4000);
 ind integer;
 t_len pls_integer;
 begin
 if dbms_lob.substr( p_img_blob, 3, 1 ) != utl_raw.cast_to_raw( 'GIF' )
 then
 return null;
 end if;
 ind := 7;
 buf := dbms_lob.substr( p_img_blob, 7, 7 ); -- Logical Screen Descriptor
 ind := ind + 7;
 img.color_res := raw2num( utl_raw.bit_and( utl_raw.substr( buf, 5, 1 ), hextoraw( '70' ) ) ) / 16 + 1;
 img.color_res := 8;
 if raw2num( buf, 5, 1 ) > 127
 then
 t_len := 3 * power( 2, raw2num( utl_raw.bit_and( utl_raw.substr( buf, 5, 1 ), hextoraw( '07' ) ) ) + 1 );
 img.color_tab := dbms_lob.substr( p_img_blob, t_len, ind ); -- Global Color Table
 ind := ind + t_len;
 end if;
 --
 loop
 case dbms_lob.substr( p_img_blob, 1, ind )
 when hextoraw( '3B' ) -- trailer
 then
 exit;
 when hextoraw( '21' ) -- extension
 then
 if dbms_lob.substr( p_img_blob, 1, ind + 1 ) = hextoraw( 'F9' )
 then -- Graphic Control Extension
 if utl_raw.bit_and( dbms_lob.substr( p_img_blob, 1, ind + 3 ), hextoraw( '01' ) ) = hextoraw( '01' )
 then -- Transparent Color Flag set
 img.transparancy_index := blob2num( p_img_blob, 1, ind + 6 );
 end if;
 end if;
 ind := ind + 2; -- skip sentinel + label
 loop
 t_len := blob2num( p_img_blob, 1, ind ); -- Block Size
 exit when t_len = 0;
 ind := ind + 1 + t_len; -- skip Block Size + Data Sub-block
 end loop;
 ind := ind + 1; -- skip last Block Size
 when hextoraw( '2C' ) -- image
 then
 declare
 img_blob blob;
 min_code_size pls_integer;
 code_size pls_integer;
 flags raw(1);
 begin
 img.width := utl_raw.cast_to_binary_integer( dbms_lob.substr( p_img_blob, 2, ind + 5 )
 , utl_raw.little_endian
 );
 img.height := utl_raw.cast_to_binary_integer( dbms_lob.substr( p_img_blob, 2, ind + 7 )
 , utl_raw.little_endian
 );
 img.greyscale := false;
 ind := ind + 1 + 8; -- skip sentinel + img sizes
 flags := dbms_lob.substr( p_img_blob, 1, ind );
 if utl_raw.bit_and( flags, hextoraw( '80' ) ) = hextoraw( '80' )
 then
 t_len := 3 * power( 2, raw2num( utl_raw.bit_and( flags, hextoraw( '07' ) ) ) + 1 );
 img.color_tab := dbms_lob.substr( p_img_blob, t_len, ind + 1 ); -- Local Color Table
 end if;
 ind := ind + 1; -- skip image Flags
 min_code_size := blob2num( p_img_blob, 1, ind );
 ind := ind + 1; -- skip LZW Minimum Code Size
 dbms_lob.createtemporary( img_blob, true );
 loop
 t_len := blob2num( p_img_blob, 1, ind ); -- Block Size
 exit when t_len = 0;
 dbms_lob.append( img_blob, dbms_lob.substr( p_img_blob, t_len, ind + 1 ) ); -- Data Sub-block
 ind := ind + 1 + t_len; -- skip Block Size + Data Sub-block
 end loop;
 ind := ind + 1; -- skip last Block Size
 img.pixels := lzw_decompress( img_blob, min_code_size + 1 );
 --
 if utl_raw.bit_and( flags, hextoraw( '40' ) ) = hextoraw( '40' )
 then -- interlaced
 declare
 pass pls_integer;
 pass_ind tp_pls_tab;
 begin
 dbms_lob.createtemporary( img_blob, true );
 pass_ind( 1 ) := 1;
 pass_ind( 2 ) := trunc( ( img.height - 1 ) / 8 ) + 1;
 pass_ind( 3 ) := pass_ind( 2 ) + trunc( ( img.height + 3 ) / 8 );
 pass_ind( 4 ) := pass_ind( 3 ) + trunc( ( img.height + 1 ) / 4 );
 pass_ind( 2 ) := pass_ind( 2 ) * img.width + 1;
 pass_ind( 3 ) := pass_ind( 3 ) * img.width + 1;
 pass_ind( 4 ) := pass_ind( 4 ) * img.width + 1;
 for i in 0 .. img.height - 1
 loop
 pass := case mod( i, 8 )
 when 0 then 1
 when 4 then 2
 when 2 then 3
 when 6 then 3
 else 4
 end;
 dbms_lob.append( img_blob, dbms_lob.substr( img.pixels, img.width, pass_ind( pass ) ) );
 pass_ind( pass ) := pass_ind( pass ) + img.width;
 end loop;
 img.pixels := img_blob;
 end;
 end if;
 --
 dbms_lob.freetemporary( img_blob );
 end;
 else
 exit;
 end case;
 end loop;
 --
 img.type := 'gif';
 return img;
 end;
 --
 function parse_img
 ( p_blob in blob
 , p_adler32 in varchar2 := null
 , p_type in varchar2 := null
 )
 return tp_img
 is
 t_img tp_img;
 begin
 t_img.type := p_type;
 if t_img.type is null
 then
 if rawtohex( dbms_lob.substr( p_blob, 8, 1 ) ) = '89504E470D0A1A0A'
 then
 t_img.type := 'png';
 elsif dbms_lob.substr( p_blob , 3, 1 ) = utl_raw.cast_to_raw( 'GIF' )
 then
 t_img.type := 'gif';
 else
 t_img.type := 'jpg';
 end if;
 end if;
 --
 t_img := case lower( t_img.type )
 when 'gif' then parse_gif( p_blob )
 when 'png' then parse_png( p_blob )
 when 'jpg' then parse_jpg( p_blob )
 else null
 end;
 --
 if t_img.type is not null
 then
 t_img.adler32 := coalesce( p_adler32, adler32( p_blob ) );
 end if;
 return t_img;
 end;
 --
 procedure put_image
 ( p_img blob
 , p_x number
 , p_y number
 , p_width number := null
 , p_height number := null
 , p_align varchar2 := 'center'
 , p_valign varchar2 := 'top'
 )
 is
 t_x number;
 t_y number;
 t_img tp_img;
 t_ind pls_integer;
 t_adler32 varchar2(8);
 begin
 if p_img is null
 then
 return;
 end if;
 t_adler32 := adler32( p_img );
 t_ind := g_images.first;
 while t_ind is not null
 loop
 exit when g_images( t_ind ).adler32 = t_adler32;
 t_ind := g_images.next( t_ind );
 end loop;
 --
 if t_ind is null
 then
 t_img := parse_img( p_img, t_adler32 );
 if t_img.adler32 is null
 then
 return;
 end if;
 t_ind := g_images.count( ) + 1;
 g_images( t_ind ) := t_img;
 end if;
 --
 t_x := case substr( upper( p_align ), 1, 1 )
 when 'L' then p_x -- left
 when 'S' then p_x -- start
 when 'R' then p_x + nvl( p_width, 0 ) - g_images( t_ind ).width -- right
 when 'E' then p_x + nvl( p_width, 0 ) - g_images( t_ind ).width -- end
 else ( p_x + nvl( p_width, 0 ) - g_images( t_ind ).width ) / 2 -- center
 end;
 t_y := case substr( upper( p_valign ), 1, 1 )
 when 'C' then ( p_y - nvl( p_height, 0 ) + g_images( t_ind ).height ) / 2 -- center
 when 'B' then p_y - nvl( p_height, 0 ) + g_images( t_ind ).height -- bottom
 else p_y -- top
 end;
 --
 txt2page( 'q ' || to_char_round( least( nvl( p_width, g_images( t_ind ).width ), g_images( t_ind ).width ) )
 || ' 0 0 ' || to_char_round( least( nvl( p_height, g_images( t_ind ).height ), g_images( t_ind ).height ) )
 || ' ' || to_char_round( t_x ) || ' ' || to_char_round( t_y )
 || ' cm /I' || to_char( t_ind ) || ' Do Q'
 );
 end;
 --
 procedure put_image
 ( p_dir varchar2
 , p_file_name varchar2
 , p_x number
 , p_y number
 , p_width number := null
 , p_height number := null
 , p_align varchar2 := 'center'
 , p_valign varchar2 := 'top'
 )
 is
 t_blob blob;
 begin
 t_blob := file2blob( p_dir
 , p_file_name
 );
 put_image( t_blob
 , p_x
 , p_y
 , p_width
 , p_height
 , p_align
 , p_valign
 );
 dbms_lob.freetemporary( t_blob );
 end;
 --
 procedure put_image
 ( p_url varchar2
 , p_x number
 , p_y number
 , p_width number := null
 , p_height number := null
 , p_align varchar2 := 'center'
 , p_valign varchar2 := 'top'
 )
 is
 t_blob blob;
 begin
 t_blob := httpuritype( p_url ).getblob( );
 put_image( t_blob
 , p_x
 , p_y
 , p_width
 , p_height
 , p_align
 , p_valign
 );
 dbms_lob.freetemporary( t_blob );
 end;
 --
 procedure set_page_proc( p_src clob )
 is
 begin
 g_page_prcs( g_page_prcs.count ) := p_src;
 end;
 --
 procedure cursor2table
 ( p_c integer
 , p_widths tp_col_widths := null
 , p_headers tp_headers := null
 )
 is
 t_col_cnt integer;
 $IF DBMS_DB_VERSION.VER_LE_10 $THEN
 t_desc_tab dbms_sql.desc_tab2;
 $ELSE
 t_desc_tab dbms_sql.desc_tab3;
 $END
 d_tab dbms_sql.date_table;
 n_tab dbms_sql.number_table;
 v_tab dbms_sql.varchar2_table;
 t_bulk_size pls_integer := 200;
 t_r integer;
 t_cur_row pls_integer;
 type tp_integer_tab is table of integer;
 t_chars tp_integer_tab := tp_integer_tab( 1, 8, 9, 96, 112 );
 t_dates tp_integer_tab := tp_integer_tab( 12, 178, 179, 180, 181 , 231 );
 t_numerics tp_integer_tab := tp_integer_tab( 2, 100, 101 );
 t_widths tp_col_widths;
 t_tmp number;
 t_x number;
 t_y number;
 t_start_x number;
 t_lineheight number;
 t_padding number := 2;
 t_num_format varchar2(100) := 'tm9';
 t_date_format varchar2(100) := 'dd.mm.yyyy';
 t_txt varchar2(32767);
 c_rf number := 0.2; -- raise factor of text above cell bottom
 --
 procedure show_header
 is
 begin
 if p_headers is not null and p_headers.count > 0
 then
 t_x := t_start_x;
 for c in 1 .. t_col_cnt
 loop
 rect( t_x, t_y, t_widths( c ), t_lineheight );
 if c <= p_headers.count
 then
 put_txt( t_x + t_padding, t_y + c_rf * t_lineheight, p_headers( c ) );
 end if;
 t_x := t_x + t_widths( c );
 end loop;
 t_y := t_y - t_lineheight;
 end if;
 end;
 --
 begin
 $IF DBMS_DB_VERSION.VER_LE_10 $THEN
 dbms_sql.describe_columns2( p_c, t_col_cnt, t_desc_tab );
 $ELSE
 dbms_sql.describe_columns3( p_c, t_col_cnt, t_desc_tab );
 $END
 if p_widths is null or p_widths.count < t_col_cnt
 then
 t_tmp := get( c_get_page_width ) - get( c_get_margin_left ) - get( c_get_margin_right );
 t_widths := tp_col_widths();
 t_widths.extend( t_col_cnt );
 for c in 1 .. t_col_cnt
 loop
 t_widths( c ) := round( t_tmp / t_col_cnt, 1 );
 end loop;
 else
 t_widths := p_widths;
 end if;
 --
 if get( c_get_current_font ) is null
 then
 set_font( 'helvetica', 12 );
 end if;
 --
 for c in 1 .. t_col_cnt
 loop
 case
 when t_desc_tab( c ).col_type member of t_numerics
 then
 dbms_sql.define_array( p_c, c, n_tab, t_bulk_size, 1 );
 when t_desc_tab( c ).col_type member of t_dates
 then
 dbms_sql.define_array( p_c, c, d_tab, t_bulk_size, 1 );
 when t_desc_tab( c ).col_type member of t_chars
 then
 dbms_sql.define_array( p_c, c, v_tab, t_bulk_size, 1 );
 else
 null;
 end case;
 end loop;
 --
 t_start_x := get( c_get_margin_left );
 t_lineheight := get( c_get_fontsize ) * 1.2;
 t_y := coalesce( get( c_get_y ) - t_lineheight, get( c_get_page_height ) - get( c_get_margin_top ) ) - t_lineheight;
 --
 show_header;
 --
 loop
 t_r := dbms_sql.fetch_rows( p_c );
 for i in 0 .. t_r - 1
 loop
 if t_y < get( c_get_margin_bottom )
 then
 new_page;
 t_y := get( c_get_page_height ) - get( c_get_margin_top ) - t_lineheight;
 show_header;
 end if;
 t_x := t_start_x;
 for c in 1 .. t_col_cnt
 loop
 case
 when t_desc_tab( c ).col_type member of t_numerics
 then
 n_tab.delete;
 dbms_sql.column_value( p_c, c, n_tab );
 rect( t_x, t_y, t_widths( c ), t_lineheight );
 t_txt := to_char( n_tab( i + n_tab.first() ), t_num_format );
 if t_txt is not null
 then
 put_txt( t_x + t_widths( c ) - t_padding - str_len( t_txt ), t_y + c_rf * t_lineheight, t_txt );
 end if;
 t_x := t_x + t_widths( c );
 when t_desc_tab( c ).col_type member of t_dates
 then
 d_tab.delete;
 dbms_sql.column_value( p_c, c, d_tab );
 rect( t_x, t_y, t_widths( c ), t_lineheight );
 t_txt := to_char( d_tab( i + d_tab.first() ), t_date_format );
 if t_txt is not null
 then
 put_txt( t_x + t_padding, t_y + c_rf * t_lineheight, t_txt );
 end if;
 t_x := t_x + t_widths( c );
 when t_desc_tab( c ).col_type member of t_chars
 then
 v_tab.delete;
 dbms_sql.column_value( p_c, c, v_tab );
 rect( t_x, t_y, t_widths( c ), t_lineheight );
 t_txt := v_tab( i + v_tab.first() );
 if t_txt is not null
 then
 put_txt( t_x + t_padding, t_y + c_rf * t_lineheight, t_txt );
 end if;
 t_x := t_x + t_widths( c );
 else
 null;
 end case;
 end loop;
 t_y := t_y - t_lineheight;
 end loop;
 exit when t_r != t_bulk_size;
 end loop;
 g_y := t_y;
 end;
 --
 procedure query2table
 ( p_query varchar2
 , p_widths tp_col_widths := null
 , p_headers tp_headers := null
 )
 is
 t_cx integer;
 t_dummy integer;
 begin
 t_cx := dbms_sql.open_cursor;
 dbms_sql.parse( t_cx, p_query, dbms_sql.native );
 t_dummy := dbms_sql.execute( t_cx );
 cursor2table( t_cx, p_widths, p_headers );
 dbms_sql.close_cursor( t_cx );
 end;
 $IF not DBMS_DB_VERSION.VER_LE_10 $THEN
 --
 procedure refcursor2table
 ( p_rc sys_refcursor
 , p_widths tp_col_widths := null
 , p_headers tp_headers := null
 )
 is
 t_cx integer;
 t_rc sys_refcursor;
 begin
 t_rc := p_rc;
 t_cx := dbms_sql.to_cursor_number( t_rc );
 cursor2table( t_cx, p_widths, p_headers );
 dbms_sql.close_cursor( t_cx );
 end;
 $END
 --
 procedure pr_goto_page( i_npage number )
 is
 begin
 if i_npage <= g_pages.count
 then
 g_page_nr := i_npage - 1;
 end if;
 end;
 --
 procedure pr_goto_current_page
 is
 begin
 g_page_nr := null;
 end;
 end;
 /

3. Install UTL_MAIL procedure and send email using PL_SQL procedure

To install UTL_MAIL:

sqlplus sys/<pwd>

 @$ORACLE_HOME/rdbms/admin/utlmail.sql
 @$ORACLE_HOME/rdbms/admin/prvtmail.plb

sqlplus tctreport/tctreport

grant execute on sys.utl_mail to tctreport;

— change ‘filenm’ to your filename change ‘MY_DIR’ to the directory you created xslx and PDF report —
— Send PDF Report (code is in send_mail_pdf.sql) —


DECLARE
fil BFILE;
file_len PLS_INTEGER;
MAX_LINE_WIDTH PLS_INTEGER := 54;
buf RAW(2100);
amt BINARY_INTEGER := 2000;
pos PLS_INTEGER := 1; /* pointer for each piece */
filepos PLS_INTEGER := 1; /* pointer for the file */
filenm VARCHAR2(50) := 'my.xlsx'; /* binary file attachment */
data RAW(2100);
chunks PLS_INTEGER;
len PLS_INTEGER;
modulo PLS_INTEGER;
pieces PLS_INTEGER;
err_num NUMBER;
err_msg VARCHAR2(100);
resultraw RAW(32000);

BEGIN
EXECUTE IMMEDIATE 'ALTER SESSION SET smtp_out_server = ''172.21.103.8''';
/* Assign the file a handle */
fil := BFILENAME('MY_DIR', filenm);

/* Get the length of the file in bytes */
file_len := dbms_lob.getlength(fil);

/* Get the remainer when we divide by amt */
modulo := mod(file_len, amt);

/* How many pieces? */
pieces := trunc(file_len / amt);
if (modulo &lt;&gt; 0) then
pieces := pieces + 1;
end if;

/* Open the file */
dbms_lob.fileopen(fil, dbms_lob.file_readonly);

/* Read the first amt into the buffer */
dbms_lob.read(fil, amt, filepos, buf);

/* For each piece of the file . . . */
FOR i IN 1..pieces LOOP

/* Position file pointer for next read */
filepos := i * amt + 1;

/* Calculate remaining file length */
file_len := file_len - amt;

/* Stick the buffer contents into data */
data := utl_raw.concat(data, buf);

/* Calculate the number of chunks in this piece */
chunks := trunc(utl_raw.length(data) / MAX_LINE_WIDTH);

/* Don't want too many chunks */
IF (i &lt;&gt; pieces) THEN
chunks := chunks - 1;
END IF;

/* For each chunk in this piece . . . */
FOR j IN 0..chunks LOOP

/* Position ourselves in this piece */
pos := j * MAX_LINE_WIDTH + 1;

/* Is this the last chunk in this piece? */
IF (j &lt;&gt; chunks) THEN
len := MAX_LINE_WIDTH;
ELSE
len := utl_raw.length(data) - pos + 1;
IF (len &gt; MAX_LINE_width) THEN
len := MAX_LINE_WIDTH;
END IF;
END IF;
/* If we got something, let's write it */
IF (len &gt; 0 ) THEN

resultraw := resultraw || utl_raw.substr(data, pos, len);
END IF;
END LOOP;

/* Point at the rest of the data buffer */
IF (pos + len &lt;= utl_raw.length(data)) THEN
data := utl_raw.substr(data, pos + len);
ELSE
data := NULL;
END IF;

/* We're running out of file, only get the rest of it */
if (file_len &lt; amt and file_len &gt; 0) then
amt := file_len;
end if;

/* Read the next amount into the buffer */
dbms_lob.read(fil, amt, filepos, buf);

END LOOP;

/* Don't forget to close the file */
dbms_lob.fileclose(fil);

UTL_MAIL.SEND_ATTACH_RAW(sender =&gt; 'sendfrom@email.com', recipients =&gt; 'sendto@email.com', subject =&gt; ' Daily  Report', message =&gt; 'Hello World', attachment =&gt; resultraw, att_filename =&gt; 'my.xlsx');

END;
/

— Send PDF Report (code is in send_mail_pdf.sql )–


DECLARE
fil BFILE;
file_len PLS_INTEGER;
MAX_LINE_WIDTH PLS_INTEGER := 54;
buf RAW(2100);
amt BINARY_INTEGER := 2000;
pos PLS_INTEGER := 1; /* pointer for each piece */
filepos PLS_INTEGER := 1; /* pointer for the file */
filenm VARCHAR2(50) := 'my.pdf'; /* binary file attachment */
data RAW(2100);
chunks PLS_INTEGER;
len PLS_INTEGER;
modulo PLS_INTEGER;
pieces PLS_INTEGER;
err_num NUMBER;
err_msg VARCHAR2(100);
resultraw RAW(32000);

BEGIN
EXECUTE IMMEDIATE 'ALTER SESSION SET smtp_out_server = ''172.21.103.8''';
/* Assign the file a handle */
fil := BFILENAME('MY_DIR', filenm);

/* Get the length of the file in bytes */
file_len := dbms_lob.getlength(fil);

/* Get the remainer when we divide by amt */
modulo := mod(file_len, amt);

/* How many pieces? */
pieces := trunc(file_len / amt);
if (modulo &lt;&gt; 0) then
pieces := pieces + 1;
end if;

/* Open the file */
dbms_lob.fileopen(fil, dbms_lob.file_readonly);

/* Read the first amt into the buffer */
dbms_lob.read(fil, amt, filepos, buf);

/* For each piece of the file . . . */
FOR i IN 1..pieces LOOP

/* Position file pointer for next read */
filepos := i * amt + 1;

/* Calculate remaining file length */
file_len := file_len - amt;

/* Stick the buffer contents into data */
data := utl_raw.concat(data, buf);

/* Calculate the number of chunks in this piece */
chunks := trunc(utl_raw.length(data) / MAX_LINE_WIDTH);

/* Don't want too many chunks */
IF (i &lt;&gt; pieces) THEN
chunks := chunks - 1;
END IF;

/* For each chunk in this piece . . . */
FOR j IN 0..chunks LOOP

/* Position ourselves in this piece */
pos := j * MAX_LINE_WIDTH + 1;

/* Is this the last chunk in this piece? */
IF (j &lt;&gt; chunks) THEN
len := MAX_LINE_WIDTH;
ELSE
len := utl_raw.length(data) - pos + 1;
IF (len &gt; MAX_LINE_width) THEN
len := MAX_LINE_WIDTH;
END IF;
END IF;
/* If we got something, let's write it */
IF (len &gt; 0 ) THEN

resultraw := resultraw || utl_raw.substr(data, pos, len);
END IF;
END LOOP;

/* Point at the rest of the data buffer */
IF (pos + len &lt;= utl_raw.length(data)) THEN
data := utl_raw.substr(data, pos + len);
ELSE
data := NULL;
END IF;

/* We're running out of file, only get the rest of it */
if (file_len &lt; amt and file_len &gt; 0) then
amt := file_len;
end if;

/* Read the next amount into the buffer */
dbms_lob.read(fil, amt, filepos, buf);

END LOOP;

/* Don't forget to close the file */
dbms_lob.fileclose(fil);

UTL_MAIL.SEND_ATTACH_RAW(sender =&gt; 'sendfrom@email.com', recipients =&gt; 'sendto@email.com', subject =&gt; ' Daily  Report', message =&gt; 'Hello World', attachment =&gt; resultraw, att_filename =&gt; 'my.pdf');

END;
/

4. Brief Execution of Steps

$ sqlplus tctreport/tctreport

 @generate_excel.sql

PL/SQL procedure successfully completed.

 @generate_pdf.sql

PL/SQL procedure successfully completed.

 @send_mail_excel.sql

PL/SQL procedure successfully completed.

 @send_mail_pdf.sql

PL/SQL procedure successfully completed.

Check ASM Diskgroup Space and Directory Size

The script below can be used to check the Disk Group Space Free and also Check Directory sizes for each Disk Group

The script is written by somebody at Pythian but i cannot re-collect the original link to the blog.

eg:
./asmcmd_du.sh

DiskGroup Total_MB Free_MB % Free
——— ——– ——- ——
DATAC1 15962112 11215880 70
DBFS_DG 415296 403740 97
RECOC1 3996000 3460272 86

./asmcmd_du.sh DATAC1

DiskGroup Total_MB Free_MB % Free
——— ——– ——- ——
DATAC1 15962112 10155732 63

DATAC1 subdirectories size

Subdir Used MB Mirror MB
—— ——- ———
CARATST/ 55646 111356
ECCTST/ 174912 349856
—— ——- ———
Total 2799978 5600788

Script Below :

#!/bin/bash
# Shadab Mohammad -- 2016
#
# - If no parameter specified, show a du of each DiskGroup
# - If a parameter, print a du of each subdirectory
#

D=$1

#
# Colored thresholds (Red, Yellow, Green)
#
CRITICAL=90
WARNING=75

#
# Set the ASM env
#
ORACLE_SID=`ps -ef | grep pmon | grep asm | awk '{print $NF}' | sed s'/asm_pmon_//' | egrep "^[+]"`
export ORAENV_ASK=NO
. oraenv > /dev/null 2>&1

#
# A quick list of what is running on the server
#
ps -ef | grep pmon | grep -v grep | awk '{print $NF}' | sed s'/.*_pmon_//' | egrep "^([+]|[Aa-Zz])" | sort | awk -v H="`hostname -s`" '' | sed s'/, $//'

#
# Manage parameters
#
if [[ -z $D ]]
then # No directory provided, will check all the DG
DG=`asmcmd lsdg | grep -v State | awk '{print $NF}' | sed s'/\///'`
SUBDIR="No" # Do not show the subdirectories details if no directory is specified
else
DG=`echo $D | sed s'/\/.*$//g'`
fi

#
# A header
#
printf "\n%25s%16s%16s%14s" "DiskGroup" "Total_MB" "Free_MB" "% Free"
printf "\n%25s%16s%16s%14s\n" "---------" "--------" "-------" "------"

#
# Show DG info
#
for X in ${DG}
do
asmcmd lsdg ${X} | tail -1 |\
awk -v DG="$X" -v W="$WARNING" -v C="$CRITICAL" '\
BEGIN \
{COLOR_BEGIN = "\033[1;" ;
COLOR_END = "\033[m" ;
RED = COLOR_BEGIN"31m" ;
GREEN = COLOR_BEGIN"32m" ;
YELLOW = COLOR_BEGIN"33m" ;
COLOR = GREEN ;
}
{ FREE = sprintf("%12d", $8/$7*100) ;
if ((100-FREE) > W) {COLOR=YELLOW ;}
if ((100-FREE) > C) {COLOR=RED ;}
printf("%25s%16s%16s%s\n", DG, $7, $8, COLOR FREE COLOR_END) ; }'
done
printf "\n"

#
# Subdirs info
#
if [ -z ${SUBDIR} ]
then
(for DIR in `asmcmd ls ${D}`
do
echo ${DIR} `asmcmd du ${D}/${DIR} | tail -1`
done) | awk -v D="$D" ' BEGIN { printf("\n\t\t%40s\n\n", D " subdirectories size") ;
printf("%25s%16s%16s\n", "Subdir", "Used MB", "Mirror MB") ;
printf("%25s%16s%16s\n", "------", "-------", "---------") ;}
{
printf("%25s%16s%16s\n", $1, $2, $3) ;
use += $2 ;
mir += $3 ;
}
END { printf("\n\n%25s%16s%16s\n", "------", "-------", "---------") ;
printf("%25s%16s%16s\n\n", "Total", use, mir) ;} '
fi


#************************************************************************#
#* E N D O F S O U R C E *#
#************************************************************************#

Oracle 12c Dataguard RAC Primary to RAC Standby with Dataguard Broker (on Exadata)

Setup for the Environment
——————-

Exadata X4-2 Quater Rack n Primary and Standby Site
Grid Version : 12.1.0.2
DB Home Version : 12.1.0.2

Primary, 2 Node RAC, db_unique_name = primeprd
Instance 2 : primeprd1
Instance 2 : primeprd2
TNS entry: PRIMEPRD, but below entry in tnsnames.ora files on both node with DB Home user, most likely it will be Oracle user.

PRIMEPRD =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = primaryhost.domain.com)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = primeprd)
)
)

Standby, 2 Node RAC, db_unique_name= primedr
Instance 2 : primedr1
Instance 2 : primedr2
TNS ENTRY: PRIMEDR, but below entry in tnsnames.ora files on both node with DB Home user, most likely it will be Oracle user.

PRIMEDR =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = standbyhost.domain.com)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = primedr)
)
)

1. Enable Force Logging on the Database

 alter database force logging;

Database altered.

2.1 change the below parameter in Primary database.


ALTER SYSTEM SET db_recovery_file_dest='+RECOC1' scope=both sid='*';

System altered.

alter system set LOG_ARCHIVE_CONFIG='DG_CONFIG=(primeprd,primedr)' scope=both sid='*';

alter system set LOG_ARCHIVE_DEST_1='LOCATION=USE_DB_RECOVERY_FILE_DEST VALID_FOR=(ALL_LOGFILES,ALL_ROLES) DB_UNIQUE_NAME=primeprd' scope=both sid='*';

alter system set LOG_ARCHIVE_DEST_2='SERVICE=primedr LGWR ASYNC VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAME=primedr' scope=both sid='*';

alter system set log_archive_format='%t_%s_%r.arc' scope=spfile sid='*';

alter system set log_archive_max_processes=8 scope=both sid='*';

alter system set fal_server=primedr scope=both sid='*';

alter system set fal_client=primeprd scope=both sid='*';

alter system set standby_file_management=AUTO scope=both sid='*';

alter system set db_file_name_convert=('+DATAC1/primedr/', '+DATAC1/primeprd/', '+RECOC1/primedr/', '+RECOC1/primeprd/') scope=both sid='*';

alter system set log_file_name_convert=('+DATAC1/primedr/', '+DATAC1/primeprd/', '+RECOC1/primedr/', '+RECOC1/primeprd/') scope=both sid='*';


-- Query to check if parameters are set correctly --

set linesize 500 pages 0
col value for a90
col name for a50
select name, value
from v$parameter
where name in ('db_name','db_unique_name','log_archive_config', 'log_archive_dest_1','log_archive_dest_2',
'log_archive_dest_state_1','log_archive_dest_state_2', 'remote_login_passwordfile',
'log_archive_format','log_archive_max_processes','fal_server','db_file_name_convert',
'log_file_name_convert', 'standby_file_management');

select name, value
from v$parameter
where name in ('db_name','db_unique_name','log_archive_config', 'log_archive_dest_1','log_archive_dest_2',
'log_archive_dest_state_1','log_archive_dest_state_2', 'remote_login_passwordfile',
'log_archive_format','log_archive_max_processes','fal_server','db_file_name_convert',
'log_file_name_convert', 'standby_file_management');

3.1. verify the logfile using the below querys.

select group#,THREAD#,bytes/1024/1024,status,members from v$log;
select member from v$logfile;

3.2. Add the below logfile and standby logfile in primary database, make sure you have large redolog files. In this day and age, 100MB does not really cut it.

ALTER DATABASE ADD LOGFILE THREAD 1 GROUP 1 ('+DATAC1','+RECOC1') SIZE 1G;
ALTER DATABASE ADD LOGFILE THREAD 1 GROUP 2 ('+DATAC1','+RECOC1') SIZE 1G;
ALTER DATABASE ADD LOGFILE THREAD 1 GROUP 3 ('+DATAC1','+RECOC1') SIZE 1G;
ALTER DATABASE ADD LOGFILE THREAD 1 GROUP 4 ('+DATAC1','+RECOC1') SIZE 1G;
ALTER DATABASE ADD LOGFILE THREAD 2 GROUP 5 ('+DATAC1','+RECOC1') SIZE 1G;
ALTER DATABASE ADD LOGFILE THREAD 2 GROUP 6 ('+DATAC1','+RECOC1') SIZE 1G;
ALTER DATABASE ADD LOGFILE THREAD 2 GROUP 7 ('+DATAC1','+RECOC1') SIZE 1G;
ALTER DATABASE ADD LOGFILE THREAD 2 GROUP 8 ('+DATAC1','+RECOC1') SIZE 1G;

 select * from v$standby_log;

-- Add Standby Redolog files, number of standby redo log files = Redo logfile Groups + 2 --

ALTER DATABASE ADD STANDBY LOGFILE THREAD 1 GROUP 9 ('+DATAC1','+RECOC1') SIZE 1G;
ALTER DATABASE ADD STANDBY LOGFILE THREAD 1 GROUP 10 ('+DATAC1','+RECOC1') SIZE 1G;
ALTER DATABASE ADD STANDBY LOGFILE THREAD 1 GROUP 11 ('+DATAC1','+RECOC1') SIZE 1G;
ALTER DATABASE ADD STANDBY LOGFILE THREAD 1 GROUP 12 ('+DATAC1','+RECOC1') SIZE 1G;
ALTER DATABASE ADD STANDBY LOGFILE THREAD 1 GROUP 13 ('+DATAC1','+RECOC1') SIZE 1G;
ALTER DATABASE ADD STANDBY LOGFILE THREAD 2 GROUP 14 ('+DATAC1','+RECOC1') SIZE 1G;
ALTER DATABASE ADD STANDBY LOGFILE THREAD 2 GROUP 15 ('+DATAC1','+RECOC1') SIZE 1G;
ALTER DATABASE ADD STANDBY LOGFILE THREAD 2 GROUP 16 ('+DATAC1','+RECOC1') SIZE 1G;
ALTER DATABASE ADD STANDBY LOGFILE THREAD 2 GROUP 17 ('+DATAC1','+RECOC1') SIZE 1G;
ALTER DATABASE ADD STANDBY LOGFILE THREAD 2 GROUP 18 ('+DATAC1','+RECOC1') SIZE 1G;

4. Take the rman backup using below command.

rman target / nocatalog
run
{
sql 'alter system archive log current';
backup as compressed backupset database plus archivelog format '/u03/rmanbkp/online/Primary_bkp_for_stndby_%U';
backup current controlfile for standby format '/u03/rmanbkp/online/stby.ctl';
sql 'alter system archive log current';
}

5.1. create the init file using the below command in primary database.

create pfile='/u03/rmanbkp/prime/pfile_for_standby.txt' from spfile;

— Primary PFILE —

primeprd1.__data_transfer_cache_size=0
primeprd2.__data_transfer_cache_size=0
primeprd1.__db_cache_size=7046430720
primeprd2.__db_cache_size=7147094016
primeprd1.__java_pool_size=67108864
primeprd2.__java_pool_size=67108864
primeprd1.__large_pool_size=301989888
primeprd2.__large_pool_size=301989888
primeprd2.__oracle_base='/u03/app/oracle'#ORACLE_BASE set from environment
primeprd1.__oracle_base='/u03/app/oracle'#ORACLE_BASE set from environment
primeprd1.__pga_aggregate_target=3221225472
primeprd2.__pga_aggregate_target=3221225472
primeprd1.__sga_target=9663676416
primeprd2.__sga_target=9663676416
primeprd1.__shared_io_pool_size=469762048
primeprd2.__shared_io_pool_size=469762048
primeprd1.__shared_pool_size=1644167168
primeprd2.__shared_pool_size=1577058304
primeprd1.__streams_pool_size=100663296
primeprd2.__streams_pool_size=67108864
*.audit_file_dest='/u03/app/oracle/admin/primeprd/adump'
*.audit_trail='db'
*.cluster_database=TRUE
*.compatible='12.1.0.2.0'
*.control_files='+DATAC1/PRIMEPRD/CONTROLFILE/current.660.914322763','+DATAC1/PRIMEPRD/CONTROLFILE/current.665.914322763'
*.cpu_count=16
*.db_block_size=8192
*.db_create_file_dest='+DATAC1'
*.db_domain=''
*.db_file_name_convert='+DATAC1/primedr/','+DATAC1/primeprd/','+RECOC1/primedr/','+RECOC1/primeprd/'
*.db_name='primeprd'
*.db_recovery_file_dest='+DATAC1'
*.db_recovery_file_dest_size=536870912000
*.db_writer_processes=6
*.ddl_lock_timeout=30
*.diagnostic_dest='/u03/app/oracle'
*.dispatchers='(PROTOCOL=TCP) (SERVICE=primeprdXDB)'
*.fal_client='primeprd'
*.fal_server='primedr'
primeprd2.instance_number=2
primeprd1.instance_number=1
*.log_archive_config='dg_config=(primeprd,primedr)'
*.log_archive_dest_1='LOCATION=+RECOC1 valid_for=(ALL_LOGFILES,ALL_ROLES) db_unique_name=primeprd'
*.log_archive_dest_2='service=primedr LGWR ASYNC valid_for=(ONLINE_LOGFILE,PRIMARY_ROLE) db_unique_name=primedr'
*.log_archive_dest_state_1='ENABLE'
*.log_archive_dest_state_2='ENABLE'
*.log_archive_format='log%t_%s_%r.arc'
*.log_file_name_convert='+DATAC1/primedr/','+DATAC1/primeprd/','+RECOC1/primedr/','+RECOC1/primeprd/'
*.nls_length_semantics='CHAR'
*.open_cursors=2000
*.optimizer_adaptive_features=FALSE
*.pga_aggregate_target=3072m
*.processes=1500
*.remote_login_passwordfile='exclusive'
*.resource_manager_cpu_allocation=48
*.resource_manager_plan='DEFAULT'
*.session_cached_cursors=100
*.sessions=2272
*.sga_max_size=17179869184
*.sga_target=9216m
*.standby_file_management='AUTO'
*.temp_undo_enabled=TRUE
primeprd2.thread=2
primeprd1.thread=1
primeprd2.undo_tablespace='UNDOTBS2'
primeprd1.undo_tablespace='UNDOTBS1'

— DR PFILE —

primedr1.__data_transfer_cache_size=0
primedr2.__data_transfer_cache_size=0
primedr1.__db_cache_size=7046430720
primedr2.__db_cache_size=7147094016
primedr1.__java_pool_size=67108864
primedr2.__java_pool_size=67108864
primedr1.__large_pool_size=301989888
primedr2.__large_pool_size=301989888
primedr2.__oracle_base='/u03/app/oracle'#ORACLE_BASE set from environment
primedr1.__oracle_base='/u03/app/oracle'#ORACLE_BASE set from environment
primedr1.__pga_aggregate_target=3221225472
primedr2.__pga_aggregate_target=3221225472
primedr1.__sga_target=9663676416
primedr2.__sga_target=9663676416
primedr1.__shared_io_pool_size=469762048
primedr2.__shared_io_pool_size=469762048
primedr1.__shared_pool_size=1644167168
primedr2.__shared_pool_size=1577058304
primedr1.__streams_pool_size=100663296
primedr2.__streams_pool_size=67108864
*.audit_file_dest='/u03/app/oracle/admin/primeprd/adump' # Create on Both Nodes
*.audit_trail='db'
*.cluster_database=TRUE
*.compatible='12.1.0.2.0'
#*.control_files='+DATAC1/PRIMEPRD/CONTROLFILE/current.660.914322763','+DATAC1/PRIMEPRD/CONTROLFILE/current.665.914322763'
*.cpu_count=16
*.db_block_size=8192
*.db_create_file_dest='+DATAC1'
*.db_domain=''
*.db_file_name_convert='PRIMEPRD','PRIMEDR' ##### Changed for dataguard
*.db_unique_name='primedr' ##### Changed for dataguard
*.db_name='primeprd'
*.db_recovery_file_dest='+RECOC1'
*.db_recovery_file_dest_size=536870912000
*.db_writer_processes=6
*.ddl_lock_timeout=30
*.diagnostic_dest='/u03/app/oracle'
*.dispatchers='(PROTOCOL=TCP) (SERVICE=primedrXDB)' ##### Changed for dataguard
*.fal_client='primedr' ##### Changed for dataguard
*.fal_server='primeprd' ##### Changed for dataguard
primedr2.instance_number=2
primedr1.instance_number=1
*.log_archive_config='dg_config=(primeprd,primedr)'
*.log_archive_dest_1='LOCATION=+RECOC1 valid_for=(ALL_LOGFILES,ALL_ROLES) db_unique_name=primedr' ##### Changed for dataguard
*.log_archive_dest_2='service=primeprd LGWR ASYNC valid_for=(ONLINE_LOGFILE,PRIMARY_ROLE) db_unique_name=primeprd' ##### Changed for dataguard
*.log_archive_dest_state_1='ENABLE'
*.log_archive_dest_state_2='ENABLE'
*.log_archive_format='log%t_%s_%r.arc'
*.log_file_name_convert='PRIMEPRD','PRIMEDR' ##### Changed for dataguard
*.remote_listener='exadr-scan:1521' ##### Changed for dataguard
*.nls_length_semantics='CHAR'
*.open_cursors=2000
*.optimizer_adaptive_features=FALSE
*.pga_aggregate_target=3072m
*.processes=1500
*.remote_login_passwordfile='exclusive'
*.resource_manager_cpu_allocation=48
*.resource_manager_plan='DEFAULT'
*.session_cached_cursors=100
*.sessions=2272
*.sga_max_size=17179869184
*.sga_target=9216m
*.standby_file_management='AUTO'
*.temp_undo_enabled=TRUE
primedr2.thread=2
primedr1.thread=1
primedr2.undo_tablespace='UNDOTBS2'
primedr1.undo_tablespace='UNDOTBS1'

cp -ip pfile_for_standby.txt pfile_to_apply.ora

vi pfile_to_apply.ora

— Actual PFILE after modifying all parameters —

primedr1.__data_transfer_cache_size=0
primedr2.__data_transfer_cache_size=0
primedr1.__db_cache_size=7046430720
primedr2.__db_cache_size=7147094016
primedr1.__java_pool_size=67108864
primedr2.__java_pool_size=67108864
primedr1.__large_pool_size=301989888
primedr2.__large_pool_size=301989888
primedr2.__oracle_base='/u03/app/oracle'#ORACLE_BASE set from environment
primedr1.__oracle_base='/u03/app/oracle'#ORACLE_BASE set from environment
primedr1.__pga_aggregate_target=3221225472
primedr2.__pga_aggregate_target=3221225472
primedr1.__sga_target=9663676416
primedr2.__sga_target=9663676416
primedr1.__shared_io_pool_size=469762048
primedr2.__shared_io_pool_size=469762048
primedr1.__shared_pool_size=1644167168
primedr2.__shared_pool_size=1577058304
primedr1.__streams_pool_size=100663296
primedr2.__streams_pool_size=67108864
*.audit_file_dest='/u03/app/oracle/admin/primeprd/adump'
*.audit_trail='db'
*.cluster_database=TRUE
*.compatible='12.1.0.2.0'
#*.control_files='+DATAC1/PRIMEPRD/CONTROLFILE/current.660.914322763','+DATAC1/PRIMEPRD/CONTROLFILE/current.665.914322763'
*.cpu_count=16
*.db_block_size=8192
*.db_create_file_dest='+DATAC1'
*.db_domain=''
*.db_file_name_convert='PRIMEPRD','PRIMEDR'
*.db_unique_name='primedr'
*.db_name='primeprd'
*.db_recovery_file_dest='+RECOC1'
*.db_recovery_file_dest_size=536870912000
*.db_writer_processes=6
*.ddl_lock_timeout=30
*.diagnostic_dest='/u03/app/oracle'
*.dispatchers='(PROTOCOL=TCP) (SERVICE=primedrXDB)'
*.fal_client='primedr'
*.fal_server='primeprd'
primedr2.instance_number=2
primedr1.instance_number=1
*.log_archive_config='dg_config=(primeprd,primedr)'
*.log_archive_dest_1='LOCATION=+RECOC1 valid_for=(ALL_LOGFILES,ALL_ROLES) db_unique_name=primedr'
*.log_archive_dest_2='service=primeprd LGWR ASYNC valid_for=(ONLINE_LOGFILE,PRIMARY_ROLE) db_unique_name=primeprd'
*.log_archive_dest_state_1='ENABLE'
*.log_archive_dest_state_2='ENABLE'
*.log_archive_format='log%t_%s_%r.arc'
*.log_file_name_convert='PRIMEPRD','PRIMEDR'
*.remote_listener='exadr-scan:1521'
*.nls_length_semantics='CHAR'
*.open_cursors=2000
*.optimizer_adaptive_features=FALSE
*.pga_aggregate_target=3072m
*.processes=1500
*.remote_login_passwordfile='exclusive'
*.resource_manager_cpu_allocation=48
*.resource_manager_plan='DEFAULT'
*.session_cached_cursors=100
*.sessions=2272
*.sga_max_size=17179869184
*.sga_target=9216m
*.standby_file_management='AUTO'
*.temp_undo_enabled=TRUE
primedr2.thread=2
primedr1.thread=1
primedr2.undo_tablespace='UNDOTBS2'
primedr1.undo_tablespace='UNDOTBS1'

6. Create same RMAN backup directory in DR and copy the backup Piece and init file from Production to DR server.

Also do not forget to create directory for adump in path ‘/u03/app/oracle/admin/primeprd/adump’

startup nomount pfile='/u03/rmanbkp/prime/pfile_to_apply.ora';
rman target sys/*****@primeprd auxiliary /

Recovery Manager: Release 12.1.0.2.0 - Production on Tue Jun 28 10:05:31 2016

Copyright (c) 1982, 2014, Oracle and/or its affiliates. All rights reserved.

connected to target database: PRIMEPRD (DBID=111111111111111)
connected to auxiliary database: PRIMEPRD (not mounted)

show all;

using target database control file instead of recovery catalog
RMAN configuration parameters for database with db_unique_name PRIMEPRD are:
CONFIGURE RETENTION POLICY TO REDUNDANCY 1; # default
CONFIGURE BACKUP OPTIMIZATION OFF;
CONFIGURE DEFAULT DEVICE TYPE TO 'SBT_TAPE';
CONFIGURE CONTROLFILE AUTOBACKUP ON;
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '/u03/rmanbkp/prime/autobackup_control_file_%F';
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE SBT_TAPE TO '%F'; # default
CONFIGURE DEVICE TYPE SBT_TAPE PARALLELISM 1 BACKUP TYPE TO BACKUPSET; # default
CONFIGURE DEVICE TYPE DISK PARALLELISM 1 BACKUP TYPE TO BACKUPSET; # default
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE SBT_TAPE TO 1; # default
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE SBT_TAPE TO 1; # default
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE CHANNEL DEVICE TYPE DISK FORMAT '/u03/rmanbkp/prime';
CONFIGURE MAXSETSIZE TO UNLIMITED; # default
CONFIGURE ENCRYPTION FOR DATABASE OFF; # default
CONFIGURE ENCRYPTION ALGORITHM 'AES128'; # default
CONFIGURE COMPRESSION ALGORITHM 'BASIC' AS OF RELEASE 'DEFAULT' OPTIMIZE FOR LOAD TRUE ; # default
CONFIGURE RMAN OUTPUT TO KEEP FOR 7 DAYS; # default
CONFIGURE ARCHIVELOG DELETION POLICY TO NONE; # default
CONFIGURE SNAPSHOT CONTROLFILE NAME TO '/u03/app/oracle/product/12.1.0.2/payapps/dbs/snapcf_primeprd1.f'; # default

 DUPLICATE TARGET DATABASE FOR STANDBY NOFILENAMECHECK;

9. start the MRP process using the below command in SQL prompt.

ALTER DATABASE RECOVER MANAGED STANDBY DATABASE USING CURRENT LOGFILE DISCONNECT;

10. In case if you get error while receiving logging onto standby use the below command and create password files on both nodes of production and dr

— For Oracle 12c, do not create password files with this method. Go to section below for Dataguard Broker Setup

orapwd file=/u03/app/oracle/product/12.1.0.2/payapps/dbs/orapwprimeprd1 force=y ignorecase=y
orapwd file=/u03/app/oracle/product/12.1.0.2/payapps/dbs/orapwprimeprd2 force=y ignorecase=y
orapwd file=/u03/app/oracle/product/12.1.0.2/payapps/dbs/orapwprimedr1 force=y ignorecase=y
orapwd file=/u03/app/oracle/product/12.1.0.2/payapps/dbs/orapwprimedr2 force=y ignorecase=y

select * from v$pwfile_users;

Check by logging in from sqlplus from both production site and DR site from both nodes

From DR both nodes

sqlplus sys/*****@primeprd as sysdba

From Prod Both nodes

sqlplus sys/******@primedr as sysdba

Stop and start recovery again in DR

alter database recover managed standby database cancel;

alter database recover managed standby database using current logfile disconnect from session;

select process,status from v$managed_standby;

11. Create the spfile and add the newly created control files

show parameter control_file

NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
control_file_record_keep_time integer 7
control_files string +DATAC1/PRIMEDR/CONTROLFILE/current.636.915704919, +RECOC1/PRIMEDR/CONTROLFILE/current.15794.915704923

Add the controlfile string in the pfile you created earlier called pfile_to_apply.ora

cd /u03/rmanbkp/prime/
vi pfile_to_apply.ora

*.control_files=’+DATAC1/PRIMEDR/CONTROLFILE/current.636.915704919′,’+RECOC1/PRIMEDR/CONTROLFILE/current.15794.915704923′

shutdown immediate;
ORA-01109: database not open

Database dismounted.
ORACLE instance shut down.

startup nomount pfile='/u03/rmanbkp/prime/pfile_to_apply.ora';

create spfile='+DATAC1/primedr/spfileprimedr.ora' from pfile='/u03/rmanbkp/prime/pfile_to_apply.ora';

shutdown immediate;

cd /u03/app/oracle/product/12.1.0.2/payapps/dbs/

vi initprimedr1.ora

–add only one line pointing to the SPFILE in ASM

spfile=’+DATAC1/primedr/spfileprimedr.ora’

startup mount pfile='/u03/app/oracle/product/12.1.0.2/payapps/dbs/initprimedr1.ora';

show parameter spfile

NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
spfile string +DATAC1/primedr/spfileprimedr.
ora

alter database recover managed standby database using current logfile disconnect from session;

12. Create cluster server using the below command.

srvctl add database -d primedr -o /u03/app/oracle/product/12.1.0.2/payapps -p +DATAC1/primedr/spfileprimedr.ora -r physical_standby -a DATAC1,RECOC1 -s MOUNT
srvctl add instance -d primedr -i primedr1 -n exadrdbadm01
srvctl add instance -d primedr -i primedr2 -n exadrdbadm02

srvctl add service -db onlndr -s onlnprod -preferred onlndr1,onlndr2
srvctl add service -db primedr -s primeprod -preferred primedr1,primedr2

srvctl config service -s onlnprod -db onlndr
srvctl config service -s primeprod -db primedr

srvctl stop database -d primedr

-- if gives error stop from sqlplus

srvctl start database -d primedr -o mount

— Start Recovery Again —

 alter database recover managed standby database using current logfile disconnect from session;

13.1. Add the below entries in both production nodes tnsnames.ora file as a oracle user. (Not required from ORacle 12c 12.1.0.2 onwards)

primeprd_DGMGRL =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = ********)(PORT = 1521))
(ADDRESS = (PROTOCOL = TCP)(HOST = ********)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = primeprd_DGMGRL)
)
)

13.2. Add the below entries in both DR nodes tnsnames.ora file as a oracle user.

primedr_DGMGRL =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = ********)(PORT = 1521))
(ADDRESS = (PROTOCOL = TCP)(HOST = ********)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = primedr_DGMGRL)
)
)

13.3. Add the below entries in production node1 listener.ora file as a grid user.

(SID_DESC =
(GLOBAL_DBNAME = primeprd_DGMGRL)
(ORACLE_HOME = /u03/app/oracle/product/12.1.0.2/payapps)
(SID_NAME = primeprd1)
)

13.4. Add the below entries in production node2 listener.ora file as a grid user.

(SID_DESC =
(GLOBAL_DBNAME = primeprd_DGMGRL)
(ORACLE_HOME = /u03/app/oracle/product/12.1.0.2/payapps)
(SID_NAME = primeprd2)
)

13.5. Add the below entries in DR node1 listener.ora file as a grid user.

(SID_DESC =
(GLOBAL_DBNAME = primedr_DGMGRL)
(ORACLE_HOME = /u03/app/oracle/product/12.1.0.2/payapps)
(SID_NAME = primedr1)
)

13.6. Add the below entries in DR node2 listener.ora file as a grid user.

(SID_DESC =
(GLOBAL_DBNAME = primedr_DGMGRL)
(ORACLE_HOME = /u03/app/oracle/product/12.1.0.2/payapps)
(SID_NAME = primedr2)
)

13.7. Using the below command to restart the listener.

$ srvctl stop listener
$ srvctl start listener

14.1. Set the below parameter in primary database.

alter system set dg_broker_config_file1 = '+DATAC1/PRIMEPRD/dr1primeprd.dat' scope=both sid='*';
alter system set dg_broker_config_file2 = '+DATAC1/PRIMEPRD/dr2primeprd.dat' scope=both sid='*';
alter system set dg_broker_start = true scope=both sid='*';

14.2. Set the below parameter in standby database.

alter system set dg_broker_config_file1 = '+DATAC1/PRIMEDR/dr1primedr.dat' scope=both sid='*';
alter system set dg_broker_config_file2 = '+DATAC1/PRIMEDR/dr2primedr.dat' scope=both sid='*';
alter system set dg_broker_start = true scope=both sid='*';

15.1. Configure the dataguard brocker using the below command from production database server

/home/oracle::11g- dgmgrl

connect sys/*****

create configuration dg_primeprd as primary database is primeprd connect identifier is primeprd;

add database primedr as connect identifier is primedr maintained as physical;

Configuration "dg_primeprd" created with primary database "primeprd"

add database primedr as connect identifier is primedr maintained as physical;
Error: ORA-16698: member has a LOG_ARCHIVE_DEST_n parameter with SERVICE attribute set

Failed.

remove configuration;
Removed configuration

Set the log_archive_dest_2 settings from both the Primary and Standby databases to be nothing.

alter system set log_archive_dest_2='' scope=both sid='*';

Disable then Enable the broker parameter on both the Primary and Standby databases.

— Primary

alter system set dg_broker_start=false scope=both sid='*';
alter system set dg_broker_start=true scope=both sid='*';

— Standby

alter system set dg_broker_start=false scope=both sid='*';
alter system set dg_broker_start=true scope=both sid='*';

On the Primary database create the broker configuration for the Primary and Standby database and this time it should work fine with no issues since the log archive destination 2 setting is not set, this is the workaround/solution.

/home/oracle::11g-- dgmgrl

connect sys/*****

create configuration dg_primeprd as primary database is primeprd connect identifier is primeprd;

add database primedr as connect identifier is primedr maintained as physical;

enable configuration;

Set back the log_archive_dest_2 on both production and dr

— In Production Database —

alter system set log_archive_dest_2='service=primedr LGWR ASYNC valid_for=(ONLINE_LOGFILE,PRIMARY_ROLE) db_unique_name=primedr' scope=both sid='*';

— In DR Database —

alter system set log_archive_dest_2='service=primeprd LGWR ASYNC valid_for=(ONLINE_LOGFILE,PRIMARY_ROLE) db_unique_name=primeprd' scope=both sid='*';

If in Broker you get below error

 show configuration

Configuration - dg_primeprd

Protection Mode: MaxPerformance
Members:
primeprd - Primary database
primedr - Physical standby database
Error: ORA-16664: unable to receive the result from a database

Fast-Start Failover: DISABLED

Configuration Status:
ERROR (status updated 40 seconds ago)

Check in Broker Log File.

Mon Jul 04 14:41:46 2016
Error 1017 received logging on to the standby
------------------------------------------------------------
Check that the primary and standby are using a password file
and remote_login_passwordfile is set to SHARED or EXCLUSIVE,
and that the SYS password is same in the password files.
returning error ORA-16191

Failed to send message to site . Error code is ORA-01017.

Then re-create password files in ASM in 12c like below, the correct format is pwd

Primary

srvctl config database -d primeprd
orapwd file='+DATAC1/PRIMEPRD/pwdprimeprd' entries=10 dbuniquename=primeprd password=****** force=y ignorecase=y

Standby

srvctl config database -d primedr
orapwd file='+DATAC1/PRIMEDR/pwdprimedr' entries=10 dbuniquename=primedr password=****** force=y ignorecase=y

Check configuration now and the error should have vanished and the status is success

show configuration

Configuration - dg_primeprd

Protection Mode: MaxPerformance
Members:
primeprd - Primary database
primedr - Physical standby database

Fast-Start Failover: DISABLED

Configuration Status:
SUCCESS (status updated 18 seconds ago)

— Try doing Switchover using DGMGRL Now —

 switchover to primedr
Performing switchover NOW, please wait...
Error: ORA-16644: apply instance not available

Failed.
Unable to switchover, primary database is still "primeprd"

edit database primedr set state='APPLY-ON' with apply instance='primedr1';

show database verbose primedr

Database - primedr

Role: PHYSICAL STANDBY
Intended State: APPLY-ON
Transport Lag: 0 seconds (computed 1 second ago)
Apply Lag: 0 seconds (computed 0 seconds ago)
Average Apply Rate: 6.00 KByte/s
Active Apply Rate: 755.00 KByte/s
Maximum Apply Rate: 827.00 KByte/s
Real Time Query: OFF
Instance(s):
primedr1 (apply instance)
primedr2

switchover to primedr
Performing switchover NOW, please wait...
New primary database "primedr" is opening...
Oracle Clusterware is restarting database "primeprd" ...
Switchover succeeded, new primary is "primedr"

 show configuration

Configuration - dg_primeprd

Protection Mode: MaxPerformance
Members:
primedr - Primary database
primeprd - Physical standby database

Fast-Start Failover: DISABLED

Configuration Status:

SUCCESS (status updated 40 seconds ago)

edit database primeprd set state='APPLY-ON' with apply instance='primeprd1';

show database verbose primeprd

Database - primeprd

Role: PHYSICAL STANDBY
Intended State: APPLY-ON
Transport Lag: 0 seconds (computed 0 seconds ago)
Apply Lag: 0 seconds (computed 0 seconds ago)
Average Apply Rate: 307.00 KByte/s
Active Apply Rate: 0 Byte/s
Maximum Apply Rate: 0 Byte/s
Real Time Query: OFF
Instance(s):
primeprd1 (apply instance)
primeprd2

DGMGRL

show configuration

Configuration - dg_primeprd

Protection Mode: MaxPerformance
Members:
primedr - Primary database
primeprd - Physical standby database

Fast-Start Failover: DISABLED

Configuration Status:
SUCCESS (status updated 55 seconds ago)

Connect to DR site broker to intiate switchover

switchover to primeprd ;
Performing switchover NOW, please wait...
Operation requires a connection to instance "primeprd1" on database "primeprd"
Connecting to instance "primeprd1"...
Connected as SYSDBA.
New primary database "primeprd" is opening...
Oracle Clusterware is restarting database "primedr" ...
Switchover succeeded, new primary is "primeprd

show configuration

Configuration - dg_primeprd

Protection Mode: MaxPerformance
Members:
primeprd - Primary database
primedr - Physical standby database

Fast-Start Failover: DISABLED

Configuration Status:
SUCCESS (status updated 11 seconds ago

Linux Matrix Effects Shell Script

Sometimes to have a funky time on the BASH shell you can run the below shell script

#!/bin/bash
clear
virtcent=$((`tput lines`/2))
horcent=$((`tput cols`/2-10))
tput setf 6
tput cup $virtcent $horcent && echo "entering the matrix"
sleep 1
tput cup $virtcent $horcent && echo " "
sleep 1
tput cup $virtcent $horcent && echo "entering the matrix"
sleep 1
tput cup $virtcent $horcent && echo " "
sleep 1
tput cup $virtcent $horcent && echo "connecting. "
sleep .1
tput cup $virtcent $horcent && echo "connecting.. "
sleep .1
tput cup $virtcent $horcent && echo "connecting... "
sleep .1
tput cup $virtcent $horcent && echo "connecting.... "
sleep .1
tput cup $virtcent $horcent && echo "connecting..... "
sleep .1
tput cup $virtcent $horcent && echo "connecting...... "
sleep .1
tput cup $virtcent $horcent && echo "connecting....... "
sleep .1
tput cup $virtcent $horcent && echo "connecting....... "
sleep .1
tput cup $virtcent $horcent && echo "connecting....... "
sleep .1
tput cup $virtcent $horcent && echo "connecting........ "
sleep .1
tput cup $virtcent $horcent && echo "connecting........."
sleep 1
tput cup $virtcent $horcent && echo " CONNECTED "
sleep 1
clear

echo -e "\033[2J\033[?25l"; R=`tput lines` C=`tput cols`;: $[R--] ; while true
do ( e=echo\ -e s=sleep j=$[RANDOM%C] d=$[RANDOM%R];for i in `eval $e {1..$R}`;
do c=`printf '\\\\0%o' $[RANDOM%57+33]` ### http://easyoradba.com ###
$e "\033[$[i-1];${j}H\033[32m$c\033[$i;${j}H\033[37m"$c; $s 0.1;if [ $i -ge $d ]
then $e "\033[$[i-d];${j}H ";fi;done;for i in `eval $e {$[i-d]..$R}`; #[mat!rix]
do echo -e "\033[$i;${j}f ";$s 0.1;done)& sleep 0.05;done #(c) 2016 -- [ ShadabMohammad ]

Just chmod 750 on the script and execute

$ vi matrix.sh
$ chmod 750 matrix.sh
$ matrix.sh

This is a re-worked version of the shell script available below.

http://bruxy.regnet.cz/web/linux/EN/matrix-sh/

Configuring Oracle Wallet for Multiple RAC Databases sharing same Oracle Home

1 ) Set the environment variable also via srvctl @ oracle user.

export ORACLE_UNQNAME=’$ORACLE_HOME/bin/srvctl config database |grep -w ${ORACLE_SID%?}’

srvctl setenv database -d secdev -T “ORACLE_UNQNAME=secdev”

2) Create wallet directory on both nodes @ oracle user.

mkdir -p /u01/app/oracle/WALLETS/secdev

3) Configure sqlnet.ora as follows on both nodes @ oracle user.

If the databases share the same ORACLE_HOME, they also share the same sqlnet.ora file in $TNS_ADMIN. In order to access their individual wallet, the DIRECTORY entry for the ENCRYPTION_WALLET_LOCATION needs to point each database to its own wallet location:

NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT)
ENCRYPTION_WALLET_LOCATION = (SOURCE = (METHOD = FILE) (METHOD_DATA = (DIRECTORY = /u01/app/oracle/WALLETS/$ORACLE_UNQNAME/)))

The names of the subdirectories under /u01/app/oracle/WALLETS/  reflect the ORACLE_UNQNAME names of the individual databases. That’s why we created the directory ‘secdev’ in step 2. For each Database unique name, create one directory.

4) Create the wallet by using node1 login @ oracle user.

ALTER SYSTEM SET ENCRYPTION KEY IDENTIFIED BY “*******”;

5) Open wallet by using node1 login @ oracle user.

ALTER SYSTEM SET ENCRYPTION WALLET OPEN IDENTIFIED BY “welcome1”;

6) To configure auto login for wallet by using both nodes login @ oracle user.

orapki wallet create -wallet /u01/app/oracle/WALLETS/secdev -auto_login

7) copy the below files to node2 @ oracle user.

scp ewallet.p12  node2host:/u01/app/oracle/WALLETS/secdev
8) Change permissions on directory and files in both nodes @ oracle user.

cd /u01/app/oracle/WALLETS
chmod 700 secdev
cd secdev
chmod 600 ewallet.p12

9) After initially creating the encryption wallet (and optionally a (local) auto-open wallet), navigate to the directory that stores the Oracle Wallet and set the ‘immutable’ bit with: on both nodes @ root user.

# chattr +i ewallet.p12
# chattr +i cwallet.sso
10. You can have different wallets for different databases, all we have to do this create the directories for the unique name of databases and set the environment using srvctl utlity
ENCRYPTION_WALLET_LOCATION = (SOURCE = (METHOD = FILE) (METHOD_DATA = (DIRECTORY = /orabin/app/oracle/WALLETS/$ORACLE_UNQNAME/)))

srvctl setenv database -d testdb -T “ORACLE_UNQNAME=testdb”

srvctl setenv database -d ftestdb -T “ORACLE_UNQNAME=ftestdb”

mkdir -p /u01/app/oracle/WALLETS/testdb

mkdir -p /u01/app/oracle/WALLETS/ftestdb

And for the other databases  proceed as above steps

Link to Oracle Whitepaper for best practises for TDE

http://www.oracle.com/technetwork/database/security/twp-transparent-data-encryption-bes-130696.pdf

 

 

Oracle Dataguard Broker 12c with password file in ASM

Configure 12c dataguard broker using the below command onPrimary database server

primeprd – > tnsnames for primary database

primedr-> tnsnames for standby database

/home/oracle::11g–>dgmgrl

DGMGRL> connect sys/********

DGMGRL> create configuration dg_primeprd as primary database is primeprd connect identifier is primeprd;

DGMGRL> add database primedr as connect identifier is primedr maintained as physical;

Configuration “dg_primeprd” created with primary database “primeprd”

DGMGRL> add database primedr as connect identifier is primedr maintained as physical;
Error: ORA-16698: member has a LOG_ARCHIVE_DEST_n parameter with SERVICE attribute set

Failed.
DGMGRL> remove configuration;
Removed configuration
Set the log_archive_dest_2 settings from both the Primary and Standby databases to be nothing.

alter system set log_archive_dest_2=” scope=both sid=’*’;
Disable then Enable the broker parameter on both the Primary and Standby databases.

— Primary
alter system set dg_broker_start=false scope=both sid=’*’;
alter system set dg_broker_start=true scope=both sid=’*’;

— Standby
alter system set dg_broker_start=false scope=both sid=’*’;
alter system set dg_broker_start=true scope=both sid=’*’;

On the Primary database create the broker configuration for the Primary and Standby database and this time it should work fine with no issues since the log archive destination 2 setting is not set, this is the workaround/solution.

/home/oracle::11g–>dgmgrl

DGMGRL> connect sys/**********

DGMGRL> create configuration dg_primeprd as primary database is primeprd connect identifier is primeprd;

DGMGRL> add database primedr as connect identifier is primedr maintained as physical;

DGMGRL> enable configuration;
If in Broker you get below error Error: ORA-16664: unable to receive the result from a database

DGMGRL> show configuration

Configuration – dg_primeprd

Protection Mode: MaxPerformance
Members:
primeprd – Primary database
primedr – Physical standby database
Error: ORA-16664: unable to receive the result from a database

Fast-Start Failover: DISABLED

Configuration Status:
ERROR (status updated 40 seconds ago)

Check in Broker Log File.

Mon Jul 04 14:41:46 2016
Error 1017 received logging on to the standby
————————————————————
Check that the primary and standby are using a password file
and remote_login_passwordfile is set to SHARED or EXCLUSIVE,
and that the SYS password is same in the password files.
returning error ORA-16191

Failed to send message to site . Error code is ORA-01017.

Re-create password files in ASM in 12c like below, the correct format is pwd<dbuniquename>

Primary

srvctl config database -d primeprd

orapwd file=’+DATAC1/PRIMEPRD/pwdprimeprd’ entries=10 dbuniquename=primeprd password=*** force=y ignorecase=y
Standby

srvctl config database -d primedr
orapwd file=’+DATAC1/PRIMEDR/pwdprimedr’ entries=10 dbuniquename=primedr password=*** force=y ignorecase=y

DGMGRL> show configuration

Configuration – dg_primeprd

Protection Mode: MaxPerformance
Members:
primeprd – Primary database
primedr – Physical standby database

Fast-Start Failover: DISABLED

Configuration Status:
SUCCESS (status updated 18 seconds ago)

— Try Switchover Now —
DGMGRL> switchover to primedr
Performing switchover NOW, please wait…
Error: ORA-16644: apply instance not available

Failed.
Unable to switchover, primary database is still “primeprd”

DGMGRL> edit database primedr set state=’APPLY-ON’ with apply instance=’primedr1′;

DGMGRL> show database verbose primedr

Database – primedr

Role: PHYSICAL STANDBY
Intended State: APPLY-ON
Transport Lag: 0 seconds (computed 1 second ago)
Apply Lag: 0 seconds (computed 0 seconds ago)
Average Apply Rate: 6.00 KByte/s
Active Apply Rate: 755.00 KByte/s
Maximum Apply Rate: 827.00 KByte/s
Real Time Query: OFF
Instance(s):
primedr1 (apply instance)
primedr2
DGMGRL> switchover to primedr
Performing switchover NOW, please wait…
New primary database “primedr” is opening…
Oracle Clusterware is restarting database “primeprd” …
Switchover succeeded, new primary is “primedr”
DGMGRL> show configuration

Configuration – dg_primeprd

Protection Mode: MaxPerformance
Members:
primedr – Primary database
primeprd – Physical standby database

Fast-Start Failover: DISABLED

Configuration Status:
SUCCESS (status updated 40 seconds ago)
DGMGRL> edit database primeprd set state=’APPLY-ON’ with apply instance=’primeprd1′;

DGMGRL> show database verbose primeprd

Database – primeprd

Role: PHYSICAL STANDBY
Intended State: APPLY-ON
Transport Lag: 0 seconds (computed 0 seconds ago)
Apply Lag: 0 seconds (computed 0 seconds ago)
Average Apply Rate: 307.00 KByte/s
Active Apply Rate: 0 Byte/s
Maximum Apply Rate: 0 Byte/s
Real Time Query: OFF
Instance(s):
primeprd1 (apply instance)
primeprd2

DGMGRL>
DGMGRL> show configuration

Configuration – dg_primeprd

Protection Mode: MaxPerformance
Members:
primedr – Primary database
primeprd – Physical standby database

Fast-Start Failover: DISABLED

Configuration Status:
SUCCESS (status updated 55 seconds ago)

Connect to DR site broker to intiate switchover

DGMGRL> switchover to primeprd ;
Performing switchover NOW, please wait…
Operation requires a connection to instance “primeprd1” on database “primeprd”
Connecting to instance “primeprd1″…
Connected as SYSDBA.
New primary database “primeprd” is opening…
Oracle Clusterware is restarting database “primedr” …
Switchover succeeded, new primary is “primeprd

DGMGRL> show configuration

Configuration – dg_primeprd

Protection Mode: MaxPerformance
Members:
primeprd – Primary database
primedr – Physical standby database

Fast-Start Failover: DISABLED

Configuration Status:
SUCCESS (status updated 11 seconds ago

Query to check sessions writing to flashcache on Exadata

Query to check sessions writing to flashcache on Exadata
select se.sid, sn.name, s.value, se.program from v$sesstat s natural join v$statname sn left join v$session se on (s.sid = se.sid) where sn.name in (‘physical write requests optimized’, ‘cell writes to flash cache’, ‘cell overwrites in flash cache’) and s.value <> 0 order by s.sid,name;