/* $Id: quickreferenceServlet.java,v 1.1.2.3 2002/01/28 17:34:30 rp Exp $
 *
 * PDFlib/PDI client: mini imposition demo
 */

import java.io.*;
import javax.servlet.*;
import com.pdflib.pdflib;

public class quickreferenceServlet extends GenericServlet
{
    public void service (ServletRequest request, ServletResponse response) throws
	OutOfMemoryError, IOException, IllegalArgumentException,
	IndexOutOfBoundsException, ClassCastException, ArithmeticException,
	RuntimeException, InternalError, UnknownError
    {
	int font, row = 0 , col = 0 , i;
	int manual, pages;
	final int maxrow=2, maxcol=2;
	int startpage = 128, endpage = 131;
	final float width = 500, height = 770;
	int pageno;
	String infile = "PDFlib-manual.pdf";
	byte[] buf;
	ServletOutputStream output;
	pdflib p;

	p = new pdflib();

	p.open_file("");

	p.set_info("Creator", "quickreferenceServlet.java");
	p.set_info("Author", "Rainer Ploeckl");
	p.set_info("Title", "imposition demo (JavaServlet)");

	manual = p.open_pdi(infile, "", 0);
	i = 0;

	if (manual == -1){
	    System.err.println("Couldn't open input file '" + infile + "'.\n");
	    System.exit(1);
	}
	for (pageno = startpage; pageno <= endpage; pageno++) {
	    if (row == 0 && col == 0) {
		i++;
		p.begin_page(width, height);
		font = p.findfont("Helvetica-Bold", "host", 0);
		p.setfont(font, 18);
		p.set_text_pos(25, height-24);
		p.show("PDFlib 4.0 Quick Reference");
	    }

	    pages = p.open_pdi_page(manual, pageno, "");

	    if (pages == -1) {
		System.err.println("Couldn't open page " + pageno +
		    " in '" + infile + "'.\n");
		System.exit(1);
	    }

	    p.place_pdi_page(manual, width/maxcol*col,
		    height - (row + 1) * height/maxrow,
		    (float) 1/maxrow, (float) 1/maxrow);
	    p.close_pdi_page(pages);

	    col++;
	    if (col == maxcol) {
		col = 0;
		row++;
	    }
	    if (row == maxrow) {
		row = 0;
		p.end_page();
	    }
	}

	// finish the last partial page
	if (row != 0 || col != 0)
	    p.end_page();

	p.close();
	p.close_pdi(manual);
	buf = p.get_buffer();

	response.setContentType("application/pdf");
	response.setContentLength(buf.length);

	output = response.getOutputStream();
	output.write(buf);
	output.close();

    }
}
