Beispiel #1
0
int main(int argc, char *argv[])
{
	int saved = 0;

	if (argc != 3) {
		printf("Usage: extr file.pdf pageno\n");
		exit(1);
	}

	char *filename = strdup(argv[1]);
	char *dir = dirname(strdup(filename));
	int pageno = atoi(argv[2]);

	fz_context *ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
	if (!ctx) {
		fprintf(stderr, "extr: cannot create context\n");
		exit(1);
	}

	fz_var(doc);
	fz_try(ctx) {
		doc = pdf_open_document(ctx, filename);
		saved = save_attachments(pageno, dir);
	}
	fz_catch(ctx)
	{
	}

	printf("%d\n", saved);
	return 0;
}
Beispiel #2
0
PDFDocument* PDFDocument::Open(const std::string& path,
                               int page_cache_size) {
  fz_context* context = fz_new_context(nullptr, nullptr, FZ_STORE_DEFAULT);
  pdf_document* raw_pdf_document = nullptr;
  fz_try(context) {
    raw_pdf_document = pdf_open_document(context, path.c_str());
    if ((raw_pdf_document == nullptr) ||
        (!pdf_count_pages(context, raw_pdf_document))) {
      fz_throw(
          context,
          FZ_ERROR_GENERIC,
          const_cast<char*>("Cannot open document \"%s\""),
          path.c_str());
    }
  } fz_catch(context) {
    if (raw_pdf_document != nullptr) {
      pdf_drop_document(context, raw_pdf_document);
    }
    fz_drop_context(context);
    return nullptr;
  }

  PDFDocument* document = new PDFDocument(page_cache_size);
  document->_fz_context = context;
  document->_pdf_document = raw_pdf_document;
  return document;
}
Beispiel #3
0
void pdf_clean_file(fz_context *ctx, char *infile, char *outfile, char *password, pdf_write_options *opts, char *argv[], int argc)
{
	globals glo = { 0 };

	glo.ctx = ctx;

	fz_try(ctx)
	{
		glo.doc = pdf_open_document(ctx, infile);
		if (pdf_needs_password(ctx, glo.doc))
			if (!pdf_authenticate_password(ctx, glo.doc, password))
				fz_throw(glo.ctx, FZ_ERROR_GENERIC, "cannot authenticate password: %s", infile);

		/* Only retain the specified subset of the pages */
		if (argc)
			retainpages(ctx, &glo, argc, argv);

		pdf_save_document(ctx, glo.doc, outfile, opts);
	}
	fz_always(ctx)
	{
		pdf_drop_document(ctx, glo.doc);
	}
	fz_catch(ctx)
	{
		if (opts && opts->errors)
			*opts->errors = *opts->errors+1;
	}
}
Beispiel #4
0
	Document::Document (const QString& filename, fz_context *ctx, QObject *plugin)
	: MuCtx_ (ctx)
	, MuDoc_ (pdf_open_document (ctx, filename.toUtf8 ().constData ()))
	, URL_ (QUrl::fromLocalFile (filename))
	, Plugin_ (plugin)
	{
	}
Beispiel #5
0
int pdfsign_main(int argc, char **argv)
{
	fz_context *ctx;
	pdf_document *doc;
	char *password = "";
	int i, n, c;
	pdf_page *page = NULL;

	while ((c = fz_getopt(argc, argv, "p:")) != -1)
	{
		switch (c)
		{
		case 'p': password = fz_optarg; break;
		default: usage(); break;
		}
	}

	if (argc - fz_optind < 1)
		usage();

	filename = argv[fz_optind++];

	ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
	if (!ctx)
	{
		fprintf(stderr, "cannot initialize context\n");
		exit(1);
	}

	fz_var(page);

	doc = pdf_open_document(ctx, filename);
	fz_try(ctx)
	{
		if (pdf_needs_password(ctx, doc))
			if (!pdf_authenticate_password(ctx, doc, password))
				fz_warn(ctx, "cannot authenticate password: %s", filename);

		n = pdf_count_pages(ctx, doc);
		for (i = 0; i < n; ++i)
		{
			page = pdf_load_page(ctx, doc, i);
			verify_page(ctx, doc, i, page);
			fz_drop_page(ctx, (fz_page*)page);
			page = NULL;
		}
	}
	fz_always(ctx)
		pdf_drop_document(ctx, doc);
	fz_catch(ctx)
	{
		fz_drop_page(ctx, (fz_page*)page);
		fprintf(stderr, "error verify signatures: %s\n", fz_caught_message(ctx));
	}

	fz_flush_warnings(ctx);
	fz_drop_context(ctx);
	return 0;
}
Beispiel #6
0
int pdfextract_main(int argc, char **argv)
{
    char *infile;
    char *password = "";
    int c, o;

    while ((c = fz_getopt(argc, argv, "p:r")) != -1)
    {
        switch (c)
        {
        case 'p':
            password = fz_optarg;
            break;
        case 'r':
            dorgb++;
            break;
        default:
            usage();
            break;
        }
    }

    if (fz_optind == argc)
        usage();

    infile = argv[fz_optind++];

    ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
    if (!ctx)
    {
        fprintf(stderr, "cannot initialise context\n");
        exit(1);
    }

    doc = pdf_open_document(ctx, infile);
    if (pdf_needs_password(ctx, doc))
        if (!pdf_authenticate_password(ctx, doc, password))
            fz_throw(ctx, FZ_ERROR_GENERIC, "cannot authenticate password: %s", infile);

    if (fz_optind == argc)
    {
        int len = pdf_count_objects(ctx, doc);
        for (o = 1; o < len; o++)
            showobject(o);
    }
    else
    {
        while (fz_optind < argc)
        {
            showobject(atoi(argv[fz_optind]));
            fz_optind++;
        }
    }

    pdf_close_document(ctx, doc);
    fz_flush_warnings(ctx);
    fz_drop_context(ctx);
    return 0;
}
Beispiel #7
0
int pdfposter_main(int argc, char **argv)
{
	char *infile;
	char *outfile = "out.pdf";
	char *password = "";
	int c;
	fz_write_options opts = { 0 };
	pdf_document *doc;
	fz_context *ctx;

	opts.do_incremental = 0;
	opts.do_garbage = 0;
	opts.do_expand = 0;
	opts.do_ascii = 0;
	opts.do_linear = 0;

	while ((c = fz_getopt(argc, argv, "x:y:")) != -1)
	{
		switch (c)
		{
		case 'p': password = fz_optarg; break;
		case 'x': x_factor = atoi(fz_optarg); break;
		case 'y': y_factor = atoi(fz_optarg); break;
		default: usage(); break;
		}
	}

	if (argc - fz_optind < 1)
		usage();

	infile = argv[fz_optind++];

	if (argc - fz_optind > 0 &&
		(strstr(argv[fz_optind], ".pdf") || strstr(argv[fz_optind], ".PDF")))
	{
		outfile = argv[fz_optind++];
	}

	ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
	if (!ctx)
	{
		fprintf(stderr, "cannot initialise context\n");
		exit(1);
	}

	doc = pdf_open_document(ctx, infile);
	if (pdf_needs_password(ctx, doc))
		if (!pdf_authenticate_password(ctx, doc, password))
			fz_throw(ctx, FZ_ERROR_GENERIC, "cannot authenticate password: %s", infile);

	decimatepages(ctx, doc);

	pdf_write_document(ctx, doc, outfile, &opts);

	pdf_close_document(ctx, doc);
	fz_drop_context(ctx);
	return 0;
}
Beispiel #8
0
fz_document *
fz_open_document(fz_context *ctx, char *filename)
{
	char *ext = strrchr(filename, '.');

	if (ext)
	{
		if (!fz_strcasecmp(ext, ".xps") || !fz_strcasecmp(ext, ".rels"))
			return (fz_document*) xps_open_document(ctx, filename);
		if (!fz_strcasecmp(ext, ".cbz") || !fz_strcasecmp(ext, ".zip"))
			return (fz_document*) cbz_open_document(ctx, filename);
		if (!fz_strcasecmp(ext, ".pdf"))
			return (fz_document*) pdf_open_document(ctx, filename);
	}

	/* last guess: pdf */
	return (fz_document*) pdf_open_document(ctx, filename);
}
Beispiel #9
0
fz_document *
fz_open_document(fz_context *ctx, char *filename)
{
	char *ext = strrchr(filename, '.');
	if (ext && (!fz_strcasecmp(ext, ".xps") || !fz_strcasecmp(ext, ".rels")))
		return (fz_document*) xps_open_document(ctx, filename);
	if (ext && !fz_strcasecmp(ext, ".cbz"))
		return (fz_document*) cbz_open_document(ctx, filename);
#if 0
	/* We used to only open pdf files if they ended in .pdf. For now,
	 * until we move to detecting filetypes by their content, we disable
	 * this code, and assume that any file that hasn't matched an
	 * extension already, is a PDF. */
	if (ext && !fz_strcasecmp(ext, ".pdf"))
		return (fz_document*) pdf_open_document(ctx, filename);
	fz_throw(ctx, "unknown document type: '%s'", filename);
	return NULL;
#else
	return (fz_document*) pdf_open_document(ctx, filename);
#endif
}
Beispiel #10
0
JNIEXPORT int JNICALL
Java_com_artifex_mupdf_MuPDFCore_openFile(JNIEnv * env, jobject thiz, jstring jfilename)
{
	const char *filename;
	int pages = 0;

	filename = (*env)->GetStringUTFChars(env, jfilename, NULL);
	if (filename == NULL)
	{
		LOGE("Failed to get filename");
		return 0;
	}

	/* 128 MB store for low memory devices. Tweak as necessary. */
	ctx = fz_new_context(NULL, NULL, 128 << 20);
	if (!ctx)
	{
		LOGE("Failed to initialise context");
		return 0;
	}

	xref = NULL;
	fz_try(ctx)
	{
		colorspace = fz_device_rgb;

		LOGE("Opening document...");
		fz_try(ctx)
		{
			xref = pdf_open_document(ctx, filename);
		}
		fz_catch(ctx)
		{
			fz_throw(ctx, "Cannot open document: '%s'\n", filename);
		}
		pages = pdf_count_pages(xref);
		LOGE("Done! %d pages", pages);
	}
	fz_catch(ctx)
	{
		LOGE("Failed: %s", ctx->error->message);
		pdf_close_document(xref);
		xref = NULL;
		fz_free_context(ctx);
		ctx = NULL;
	}

	return pages;
}
Beispiel #11
0
static int
pdfpages_pages(fz_context *ctx, fz_output *out, char *filename, char *password, char *argv[], int argc)
{
	enum { NO_FILE_OPENED, NO_INFO_GATHERED, INFO_SHOWN } state;
	int argidx = 0;
	pdf_document *doc = NULL;
	int ret = 0;

	state = NO_FILE_OPENED;
	while (argidx < argc)
	{
		if (state == NO_FILE_OPENED || !fz_is_page_range(ctx, argv[argidx]))
		{
			if (state == NO_INFO_GATHERED)
			{
				showpages(ctx, doc, out, "1-N");
			}

			pdf_drop_document(ctx, doc);

			filename = argv[argidx];
			fz_printf(ctx, out, "%s:\n", filename);
			doc = pdf_open_document(ctx, filename);
			if (pdf_needs_password(ctx, doc))
				if (!pdf_authenticate_password(ctx, doc, password))
					fz_throw(ctx, FZ_ERROR_GENERIC, "cannot authenticate password: %s", filename);

			state = NO_INFO_GATHERED;
		}
		else
		{
			ret |= showpages(ctx, doc, out, argv[argidx]);
			state = INFO_SHOWN;
		}

		argidx++;
	}

	if (state == NO_INFO_GATHERED)
		showpages(ctx, doc, out, "1-N");

	pdf_drop_document(ctx, doc);

	return ret;
}
Beispiel #12
0
pdf_document *openxref(fz_context *ctx, char *filename)
{
	pdf_document *xref = pdf_open_document(ctx, filename);

	fz_try(ctx)
	{
		if (pdf_needs_password(xref))
		{
			logbench("Warning: password protected document\n");
			fz_throw(ctx, "document requires password");
		}

		pdf_count_pages(xref);
	}
	fz_catch(ctx)
	{
		pdf_close_document(xref);
		fz_rethrow(ctx);
	}

	return xref;
}
Beispiel #13
0
/* Put parameters, implementation */
static int
gdev_pdf_put_params_impl(gx_device * dev, const gx_device_pdf * save_dev, gs_param_list * plist)
{
    int ecode, code;
    gx_device_pdf *pdev = (gx_device_pdf *) dev;
    float cl = (float)pdev->CompatibilityLevel;
    bool locked = pdev->params.LockDistillerParams;
    gs_param_name param_name;
    enum psdf_color_conversion_strategy save_ccs = pdev->params.ColorConversionStrategy;
  
    pdev->pdf_memory = gs_memory_stable(pdev->memory);
    /*
     * If this is a pseudo-parameter (pdfmark or DSC),
     * don't bother checking for any real ones.
     */

    {
	gs_param_string_array ppa;

	code = param_read_string_array(plist, (param_name = "pdfmark"), &ppa);
	switch (code) {
	    case 0:
		code = pdf_open_document(pdev);
		if (code < 0)
		    return code;
		code = pdfmark_process(pdev, &ppa);
		if (code >= 0)
		    return code;
		/* falls through for errors */
	    default:
		param_signal_error(plist, param_name, code);
		return code;
	    case 1:
		break;
	}

	code = param_read_string_array(plist, (param_name = "DSC"), &ppa);
	switch (code) {
	    case 0:
		code = pdf_open_document(pdev);
		if (code < 0)
		    return code;
		code = pdf_dsc_process(pdev, &ppa);
		if (code >= 0)
		    return code;
		/* falls through for errors */
	    default:
		param_signal_error(plist, param_name, code);
		return code;
	    case 1:
		break;
	}
    }
  
    /*
     * Check for LockDistillerParams before doing anything else.
     * If LockDistillerParams is true and is not being set to false,
     * ignore all resettings of PDF-specific parameters.  Note that
     * LockDistillerParams is read again, and reset if necessary, in
     * psdf_put_params.
     */
    ecode = code = param_read_bool(plist, "LockDistillerParams", &locked);
 
    if (!(locked && pdev->params.LockDistillerParams)) {
	/* General parameters. */

	{
	    int efo = 1;

	    ecode = param_put_int(plist, (param_name = ".EmbedFontObjects"), &efo, ecode);
	    if (efo != 1)
		param_signal_error(plist, param_name, ecode = gs_error_rangecheck);
	}
	{
	    int cdv = CoreDistVersion;

	    ecode = param_put_int(plist, (param_name = "CoreDistVersion"), &cdv, ecode);
	    if (cdv != CoreDistVersion)
		param_signal_error(plist, param_name, ecode = gs_error_rangecheck);
	}

	switch (code = param_read_float(plist, (param_name = "CompatibilityLevel"), &cl)) {
	    default:
		ecode = code;
		param_signal_error(plist, param_name, ecode);
	    case 0:
		/*
		 * Must be 1.2, 1.3, 1.4, or 1.5.  Per Adobe documentation, substitute
		 * the nearest achievable value.
		 */
		if (cl < (float)1.15)
		    cl = (float)1.1;
		else if (cl < (float)1.25)
		    cl = (float)1.2;
		else if (cl < (float)1.35)
		    cl = (float)1.3;
		else if (cl < (float)1.45)
		    cl = (float)1.4;
		else
		    cl = (float)1.5;
	    case 1:
		break;
	}
	{   /* HACK : gs_param_list_s::memory is documented in gsparam.h as
	       "for allocating coerced arrays". Not sure why zputdeviceparams
	       sets it to the current memory space, while the device
	       assumes to store them in the device's memory space.
	       As a hackish workaround we temporary replace it here.
	       Doing so because we don't want to change the global code now
	       because we're unable to test it with all devices.
	       Bug 688531 "Segmentation fault running pdfwrite from 219-01.ps".

	       This solution to be reconsidered after fixing 
	       the bug 688533 "zputdeviceparams specifies a wrong memory space.".
 	    */
	    gs_memory_t *mem = plist->memory;

	    plist->memory = pdev->pdf_memory;
	    code = gs_param_read_items(plist, pdev, pdf_param_items);
	    if (code < 0 ||
		(pdev->is_ps2write && (code = param_read_string(plist, "OPDFReadProcsetPath", &pdev->OPDFReadProcsetPath)) < 0) ||
		(!pdev->is_ps2write && (code = param_read_bool(plist, "ForOPDFRead", &pdev->ForOPDFRead)) < 0)
		);
	    plist->memory = mem;
	}
	if (code < 0)
	    ecode = code;
	{
	    /*
	     * Setting FirstObjectNumber is only legal if the file
	     * has just been opened and nothing has been written,
	     * or if we are setting it to the same value.
	     */
	    long fon = pdev->FirstObjectNumber;

	    if (fon != save_dev->FirstObjectNumber) {
		if (fon <= 0 || fon > 0x7fff0000 ||
		    (pdev->next_id != 0 &&
		     pdev->next_id !=
		     save_dev->FirstObjectNumber + pdf_num_initial_ids)
		    ) {
		    ecode = gs_error_rangecheck;
		    param_signal_error(plist, "FirstObjectNumber", ecode);
		}
	    }
	}
	{
	    /*
	     * Set ProcessColorModel now, because gx_default_put_params checks
	     * it.
	     */
	    static const char *const pcm_names[] = {
		"DeviceGray", "DeviceRGB", "DeviceCMYK", "DeviceN", 0
	    };
	    int pcm = -1;

	    ecode = param_put_enum(plist, "ProcessColorModel", &pcm,
				   pcm_names, ecode);
	    if (pcm >= 0) {
		pdf_set_process_color_model(pdev, pcm);
		pdf_set_initial_color(pdev, &pdev->saved_fill_color, &pdev->saved_stroke_color,
				&pdev->fill_used_process_color, &pdev->stroke_used_process_color);
	    }
	}
    }
    if (ecode < 0)
	goto fail;
    if (pdev->PDFX && pdev->PDFA) {
	ecode = gs_note_error(gs_error_rangecheck);
	param_signal_error(plist, "PDFA", ecode);
	goto fail;
    }
    if (pdev->PDFX && pdev->ForOPDFRead) {
	ecode = gs_note_error(gs_error_rangecheck);
	param_signal_error(plist, "PDFX", ecode);
	goto fail;
    }
    if (pdev->PDFA && pdev->ForOPDFRead) {
	ecode = gs_note_error(gs_error_rangecheck);
	param_signal_error(plist, "PDFA", ecode);
	goto fail;
    }
    if (pdev->PDFA)
	 pdev->HaveTransparency = false;
    /*
     * We have to set version to the new value, because the set of
     * legal parameter values for psdf_put_params varies according to
     * the version.
     */
    if (pdev->PDFX)
	cl = (float)1.3; /* Instead pdev->CompatibilityLevel = 1.2; - see below. */
    if (pdev->PDFA && cl < 1.4)
	cl = (float)1.4;
    pdev->version = (cl < 1.2 ? psdf_version_level2 : psdf_version_ll3);
    if (pdev->ForOPDFRead) {
	pdev->ResourcesBeforeUsage = true;
	pdev->HaveCFF = false;
	pdev->HavePDFWidths = false;
	pdev->HaveStrokeColor = false;
	cl = (float)1.2; /* Instead pdev->CompatibilityLevel = 1.2; - see below. */
	pdev->MaxInlineImageSize = max_long; /* Save printer's RAM from saving temporary image data.
					        Immediate images doen't need buffering. */
	pdev->version = psdf_version_level2;
    } else {
	pdev->ResourcesBeforeUsage = false;
	pdev->HaveCFF = true;
	pdev->HavePDFWidths = true;
	pdev->HaveStrokeColor = true;
    }
    pdev->ParamCompatibilityLevel = cl;
    ecode = gdev_psdf_put_params(dev, plist);
    if (ecode < 0)
	goto fail;
    if ((pdev->params.ColorConversionStrategy == ccs_CMYK &&
	 strcmp(pdev->color_info.cm_name, "DeviceCMYK")) ||
	(pdev->params.ColorConversionStrategy == ccs_sRGB &&
	  strcmp(pdev->color_info.cm_name, "DeviceRGB")) ||
	(pdev->params.ColorConversionStrategy == ccs_Gray &&
	  strcmp(pdev->color_info.cm_name, "DeviceGray"))) {
	eprintf("ColorConversionStrategy is incompatible to ProcessColorModel.\n");
	ecode = gs_note_error(gs_error_rangecheck);
	pdev->params.ColorConversionStrategy = save_ccs;
    }
    if (pdev->params.ColorConversionStrategy == ccs_UseDeviceIndependentColor) {
	if (!pdev->UseCIEColor) {
	    eprintf("Set UseCIEColor for UseDeviceIndependentColor to work properly.\n");
	    ecode = gs_note_error(gs_error_rangecheck);
	    pdev->UseCIEColor = true;
	}
    }
    if (pdev->params.ColorConversionStrategy == ccs_UseDeviceIndependentColorForImages) {
	if (!pdev->UseCIEColor) {
	    eprintf("UseDeviceDependentColorForImages is not supported. Use UseDeviceIndependentColor.\n");
	    pdev->params.ColorConversionStrategy = ccs_UseDeviceIndependentColor;
	    if (!pdev->UseCIEColor) {
		eprintf("Set UseCIEColor for UseDeviceIndependentColor to work properly.\n");
		ecode = gs_note_error(gs_error_rangecheck);
		pdev->UseCIEColor = true;
	    }
	}
    }
    if (pdev->params.ColorConversionStrategy == ccs_UseDeviceDependentColor) {
	if (!strcmp(pdev->color_info.cm_name, "DeviceCMYK")) {
	    eprintf("Replacing the deprecated device parameter value UseDeviceDependentColor with CMYK.\n");
	    pdev->params.ColorConversionStrategy = ccs_CMYK;
	} else if (!strcmp(pdev->color_info.cm_name, "DeviceRGB")) {
	    eprintf("Replacing the deprecated device parameter value UseDeviceDependentColor with sRGB.\n");
	    pdev->params.ColorConversionStrategy = ccs_sRGB;
	} else {
	    eprintf("Replacing the deprecated device parameter value UseDeviceDependentColor with Gray.\n");
	    pdev->params.ColorConversionStrategy = ccs_Gray;
	}
    }
    if (cl < 1.5 && pdev->params.ColorImage.Filter != NULL &&
	    !strcmp(pdev->params.ColorImage.Filter, "JPXEncode")) {
	eprintf("JPXEncode requires CompatibilityLevel >= 1.5 .\n");
	ecode = gs_note_error(gs_error_rangecheck);
    }
    if (cl < 1.5 && pdev->params.GrayImage.Filter != NULL &&
	    !strcmp(pdev->params.GrayImage.Filter, "JPXEncode")) {
	eprintf("JPXEncode requires CompatibilityLevel >= 1.5 .\n");
	ecode = gs_note_error(gs_error_rangecheck);
    }
    if (cl < 1.4  && pdev->params.MonoImage.Filter != NULL &&
	    !strcmp(pdev->params.MonoImage.Filter, "JBIG2Encode")) {
	eprintf("JBIG2Encode requires CompatibilityLevel >= 1.4 .\n");
	ecode = gs_note_error(gs_error_rangecheck);
    }
    if (pdev->HaveTrueTypes && pdev->version == psdf_version_level2) {
	pdev->version = psdf_version_level2_with_TT ;
    }
    /*
     * Acrobat Reader doesn't handle user-space coordinates larger than
     * MAX_USER_COORD.  To compensate for this, reduce the resolution so
     * that the page size in device space (which we equate to user space) is
     * significantly less than MAX_USER_COORD.  Note that this still does
     * not protect us against input files that use coordinates far outside
     * the page boundaries.
     */
#define MAX_EXTENT ((int)(MAX_USER_COORD * 0.9))
    /* Changing resolution or page size requires closing the device, */
    if (dev->height > MAX_EXTENT || dev->width > MAX_EXTENT) {
	double factor =
	    max(dev->height / (double)MAX_EXTENT,
		dev->width / (double)MAX_EXTENT);

	gx_device_set_resolution(dev, dev->HWResolution[0] / factor,
				 dev->HWResolution[1] / factor);
    }
#undef MAX_EXTENT
    if (pdev->FirstObjectNumber != save_dev->FirstObjectNumber) {
	if (pdev->xref.file != 0) {
	    fseek(pdev->xref.file, 0L, SEEK_SET);
	    pdf_initialize_ids(pdev);
	}
    }
    /* Handle the float/double mismatch. */
    pdev->CompatibilityLevel = (int)(cl * 10 + 0.5) / 10.0;
    return 0;
 fail:
    /* Restore all the parameters to their original state. */
    pdev->version = save_dev->version;
    pdf_set_process_color_model(pdev, save_dev->pcm_color_info_index);
    pdev->saved_fill_color = save_dev->saved_fill_color;
    pdev->saved_stroke_color = save_dev->saved_fill_color;
    {
	const gs_param_item_t *ppi = pdf_param_items;

	for (; ppi->key; ++ppi)
	    memcpy((char *)pdev + ppi->offset,
		   (char *)save_dev + ppi->offset,
		   gs_param_type_sizes[ppi->type]);
	pdev->ForOPDFRead = save_dev->ForOPDFRead;
	pdev->OPDFReadProcsetPath = save_dev->OPDFReadProcsetPath;
    }
    return ecode;
}
Beispiel #14
0
int pdfmerge_main(int argc, char **argv)
{
	pdf_write_options opts = { 0 };
	char *output = "out.pdf";
	char *flags = "";
	char *input;
	int c;

	while ((c = fz_getopt(argc, argv, "o:O:")) != -1)
	{
		switch (c)
		{
		case 'o': output = fz_optarg; break;
		case 'O': flags = fz_optarg; break;
		default: usage(); break;
		}
	}

	if (fz_optind == argc)
		usage();

	ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
	if (!ctx)
	{
		fprintf(stderr, "error: Cannot initialize MuPDF context.\n");
		exit(1);
	}

	pdf_parse_write_options(ctx, &opts, flags);

	fz_try(ctx)
	{
		doc_des = pdf_create_document(ctx);
	}
	fz_catch(ctx)
	{
		fprintf(stderr, "error: Cannot create destination document.\n");
		exit(1);
	}

	/* Step through the source files */
	while (fz_optind < argc)
	{
		input = argv[fz_optind++];
		fz_try(ctx)
		{
			pdf_drop_document(ctx, doc_src);
			doc_src = pdf_open_document(ctx, input);
			if (fz_optind == argc || !fz_is_page_range(ctx, argv[fz_optind]))
				merge_range("1-N");
			else
				merge_range(argv[fz_optind++]);
		}
		fz_catch(ctx)
		{
			fprintf(stderr, "error: Cannot merge document '%s'.\n", input);
			exit(1);
		}
	}

	fz_try(ctx)
	{
		pdf_save_document(ctx, doc_des, output, &opts);
	}
	fz_always(ctx)
	{
		pdf_drop_document(ctx, doc_des);
		pdf_drop_document(ctx, doc_src);
	}
	fz_catch(ctx)
	{
		fprintf(stderr, "error: Cannot save output file: '%s'.\n", output);
		exit(1);
	}

	fz_flush_warnings(ctx);
	fz_drop_context(ctx);
	return 0;
}
Beispiel #15
0
void pdf_ship_out (pointer p)
{
  integer page_loc;
  char j, k;

  if (tracing_output > 0)
  {
    print_nl("");
    print_ln();
    prints("Completed box being shipped out");
  }

  if (term_offset > max_print_line - 9)
    print_ln();
  else if ((term_offset > 0) || (file_offset > 0))
    print_char(' ');

  print_char('[');
  j = 9;

  while ((count(j) == 0) && (j > 0))
    decr(j);

  for (k = 0; k <= j; k++)
  {
    print_int(count(k));

    if (k < j)
      print_char('.');
  }

  update_terminal();

  if (tracing_output > 0)
  {
    print_char(']');
    begin_diagnostic();
    show_box(p);
    end_diagnostic(true);
  }

  if ((height(p) > max_dimen) || (depth(p) > max_dimen) ||
      (height(p) + depth(p) + v_offset > max_dimen) ||
      (width(p) + h_offset > max_dimen))
  {
    print_err("Huge page cannot be shipped out");
    help2("The page just created is more than 18 feet tall or",
      "more than 18 feet wide, so I suspect something went wrong.");
    error();

    if (tracing_output <= 0)
    {
      begin_diagnostic();
      print_nl("The following box has been deleted:");
      show_box(p);
      end_diagnostic(true);
    }

    goto done;
  }

  if (height(p) + depth(p) + v_offset > max_v)
    max_v = height(p) + depth(p) + v_offset;

  if (width(p) + h_offset > max_h)
    max_h = width(p) + h_offset;

  dvi_h = 0;
  dvi_v = 0;
  cur_h = h_offset;
  dvi_f = null_font;
  ensure_pdf_open();

  if (total_pages == 0)
  {
    pdf_set_version(5);
    pdf_set_compression(9);
    pdf_init_fontmaps();
    read_config_file("dvipdfmx.cfg");
    pdf_doc_set_producer("Y&YTeX 2.3.0");
    pdf_doc_set_creator("TeX");
    pdf_files_init();
    pdf_init_device(0.000015202, 2, 0);
    // TODO: pdfTeX's page width and height.
    // page_width  = pdf_page_width  != 0 ? <- : width(p)             + 2 * (pdf_h_origin + h_offset);
    // page_height = pdf_page_height != 0 ? <- : height(p) + depth(p) + 2 * (pdf_v_origin + v_offset);
    pdf_open_document(pdf_file_name, 0, 595.0, 842.0, 0, 0, (1 << 4));
    spc_exec_at_begin_document();
  }

  page_loc = dvi_offset + dvi_ptr;
  pdf_doc_begin_page(1.0, 72.0, 770.0);
  spc_exec_at_begin_page();

  last_bop = page_loc;
  cur_v = height(p) + v_offset;
  temp_ptr = p;

  if (type(p) == vlist_node)
    pdf_vlist_out();
  else
    pdf_hlist_out();

  spc_exec_at_end_page();
  pdf_doc_end_page();
  incr(total_pages);
  cur_s = -1;

done:
  if (tracing_output <= 0)
    print_char(']');

  dead_cycles = 0;
  update_terminal();

#ifdef STAT
  if (tracing_stats > 1)
  {
    print_nl("Memory usage before: ");
    print_int(var_used);
    print_char('&');
    print_int(dyn_used);
    print_char(';');
  }
#endif

  flush_node_list(p);

#ifdef STAT
  if (tracing_stats > 1)
  {
    prints(" after: ");
    print_int(var_used);
    print_char('&');
    print_int(dyn_used);
    prints("; still utouched: ");
    print_int(hi_mem_min - lo_mem_max - 1);
    print_ln();
  }
#endif
}
Beispiel #16
0
int pdfmerge_main(int argc, char **argv)
{
	pdf_write_options opts = { 0 };
	char *output = "out.pdf";
	char *infile_src;
	int c;

	while ((c = fz_getopt(argc, argv, "adlszo:")) != -1)
	{
		switch (c)
		{
		case 'o': output = fz_optarg; break;
		case 'a': opts.do_ascii ++; break;
		case 'd': opts.do_expand ^= PDF_EXPAND_ALL; break;
		case 'l': opts.do_linear ++; break;
		case 's': opts.do_clean ++; break;
		case 'z': opts.do_deflate ++; break;
		default: usage(); break;
		}
	}

	if (fz_optind == argc)
		usage();

	ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
	if (!ctx)
	{
		fprintf(stderr, "Cannot initialise context\n");
		exit(1);
	}

	fz_try(ctx)
	{
		doc_des = pdf_create_document(ctx);
	}
	fz_catch(ctx)
	{
		fprintf(stderr, "Failed to allocate destination document file %s\n", output);
		exit(1);
	}

	/* Step through the source files */
	while (fz_optind < argc)
	{
		fz_try(ctx)
		{
			infile_src = argv[fz_optind++];
			pdf_drop_document(ctx, doc_src);
			doc_src = pdf_open_document(ctx, infile_src);

			if (fz_optind == argc || !isrange(argv[fz_optind]))
				merge_range("1-");
			else
				merge_range(argv[fz_optind++]);
		}
		fz_catch(ctx)
		{
			fprintf(stderr, "Failed merging document %s\n", infile_src);
			exit(1);
		}
	}

	fz_try(ctx)
	{
		pdf_save_document(ctx, doc_des, output, &opts);
	}
	fz_always(ctx)
	{
		pdf_drop_document(ctx, doc_des);
		pdf_drop_document(ctx, doc_src);
	}
	fz_catch(ctx)
	{
		fprintf(stderr, "Error encountered during file save.\n");
		exit(1);
	}
	fz_flush_warnings(ctx);
	fz_drop_context(ctx);

	return 0;
}
Beispiel #17
0
int pdfportfolio_main(int argc, char **argv)
{
	char *password = "";
	char *outfile = NULL;
	char *outopts = "compress";
	char *infile;
	int exit_code = 0;
	int do_save = 0;
	int has_old_file = 0;
	int c;

	while ((c = fz_getopt(argc, argv, "p:o:O:")) != -1)
	{
		switch (c)
		{
		case 'p': password = fz_optarg; break;
		case 'o': outfile = fz_optarg; break;
		case 'O': outopts = fz_optarg; break;
		default: usage(); break;
		}
	}

	if (fz_optind == argc)
		usage();

	infile = argv[fz_optind++];
	if (!outfile)
		outfile = infile;

	ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
	if (!ctx)
	{
		fprintf(stderr, "cannot initialise context\n");
		exit(1);
	}

	if (fz_file_exists(ctx, infile))
	{
		doc = pdf_open_document(ctx, infile);
		if (pdf_needs_password(ctx, doc))
			if (!pdf_authenticate_password(ctx, doc, password))
				fz_throw(ctx, FZ_ERROR_GENERIC, "cannot authenticate password: %s", infile);
		has_old_file = 1;
	}
	else
	{
		doc = pdf_create_document(ctx);

		/* add a blank page */
		{
			const char *template = "BT /Tm 16 Tf 50 434 TD (This is a portfolio document.) Tj ET\n";
			const unsigned char *data;
			int size;
			fz_font *font;
			pdf_obj *font_obj, *page_obj;
			pdf_obj *resources;
			fz_buffer *contents;
			fz_rect mediabox = { 0, 0, 400, 500 };

			data = fz_lookup_base14_font(ctx, "Times-Roman", &size);
			font = fz_new_font_from_memory(ctx, "Times-Roman", data, size, 0, 0);
			font_obj = pdf_add_simple_font(ctx, doc, font, PDF_SIMPLE_ENCODING_LATIN);
			fz_drop_font(ctx, font);

			resources = pdf_add_new_dict(ctx, doc, 1);
			pdf_dict_putp_drop(ctx, resources, "Font/Tm", font_obj);

			contents = fz_new_buffer_from_shared_data(ctx, (const unsigned char *)template, strlen(template));
Beispiel #18
0
pdf_document* j_mu_open_document(void* p_ctx, const char* filename)
{
	fz_context* ctx = (fz_context*)p_ctx;
	pdf_document* doc = pdf_open_document(ctx, filename);
	return doc;
}
Beispiel #19
0
int main(int argc, char **argv)
#endif
{
	char *infile;
	char *outfile = "out.pdf";
	char *password = "";
	int c, num;
	int subset;

	while ((c = fz_getopt(argc, argv, "adfgip:")) != -1)
	{
		switch (c)
		{
		case 'p': password = fz_optarg; break;
		case 'g': dogarbage ++; break;
		case 'd': doexpand ^= expand_all; break;
		case 'f': doexpand ^= expand_fonts; break;
		case 'i': doexpand ^= expand_images; break;
		case 'a': doascii ++; break;
		default: usage(); break;
		}
	}

	if (argc - fz_optind < 1)
		usage();

	infile = argv[fz_optind++];

	if (argc - fz_optind > 0 &&
		(strstr(argv[fz_optind], ".pdf") || strstr(argv[fz_optind], ".PDF")))
	{
		outfile = argv[fz_optind++];
	}

	subset = 0;
	if (argc - fz_optind > 0)
		subset = 1;

	ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
	if (!ctx)
	{
		fprintf(stderr, "cannot initialise context\n");
		exit(1);
	}

	xref = pdf_open_document(ctx, infile);
	if (pdf_needs_password(xref))
		if (!pdf_authenticate_password(xref, password))
			fz_throw(ctx, "cannot authenticate password: %s\n", infile);

	out = fopen(outfile, "wb");
	if (!out)
		fz_throw(ctx, "cannot open output file '%s'", outfile);

	fprintf(out, "%%PDF-%d.%d\n", xref->version / 10, xref->version % 10);
	fprintf(out, "%%\316\274\341\277\246\n\n");

	uselist = fz_malloc_array(ctx, xref->len + 1, sizeof(char));
	ofslist = fz_malloc_array(ctx, xref->len + 1, sizeof(int));
	genlist = fz_malloc_array(ctx, xref->len + 1, sizeof(int));
	renumbermap = fz_malloc_array(ctx, xref->len + 1, sizeof(int));

	for (num = 0; num < xref->len; num++)
	{
		uselist[num] = 0;
		ofslist[num] = 0;
		genlist[num] = 0;
		renumbermap[num] = num;
	}

	/* Make sure any objects hidden in compressed streams have been loaded */
	preloadobjstms();

	/* Only retain the specified subset of the pages */
	if (subset)
		retainpages(argc, argv);

	/* Sweep & mark objects from the trailer */
	if (dogarbage >= 1)
		sweepobj(xref->trailer);

	/* Coalesce and renumber duplicate objects */
	if (dogarbage >= 3)
		removeduplicateobjs();

	/* Compact xref by renumbering and removing unused objects */
	if (dogarbage >= 2)
		compactxref();

	/* Make renumbering affect all indirect references and update xref */
	/* Do not renumber objects if encryption is in use, as the object
	 * numbers are baked into the streams/strings, and we can't currently
	 * cope with moving them. See bug 692627. */
	if (dogarbage >= 2 && !xref->crypt)
		renumberobjs();

	writepdf();

	if (fclose(out))
		fz_throw(ctx, "cannot close output file '%s'", outfile);

	fz_free(xref->ctx, uselist);
	fz_free(xref->ctx, ofslist);
	fz_free(xref->ctx, genlist);
	fz_free(xref->ctx, renumbermap);

	pdf_close_document(xref);
	fz_free_context(ctx);
	return 0;
}
Beispiel #20
0
int main(int argc, char **argv)
#endif
{
	enum { NO_FILE_OPENED, NO_INFO_GATHERED, INFO_SHOWN } state;
	char *filename = "";
	char *password = "";
	int show = ALL;
	int c;

	while ((c = fz_getopt(argc, argv, "mfispxd:")) != -1)
	{
		switch (c)
		{
		case 'm': if (show == ALL) show = DIMENSIONS; else show |= DIMENSIONS; break;
		case 'f': if (show == ALL) show = FONTS; else show |= FONTS; break;
		case 'i': if (show == ALL) show = IMAGES; else show |= IMAGES; break;
		case 's': if (show == ALL) show = SHADINGS; else show |= SHADINGS; break;
		case 'p': if (show == ALL) show = PATTERNS; else show |= PATTERNS; break;
		case 'x': if (show == ALL) show = XOBJS; else show |= XOBJS; break;
		case 'd': password = fz_optarg; break;
		default:
			infousage();
			break;
		}
	}

	if (fz_optind == argc)
		infousage();

	ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
	if (!ctx)
	{
		fprintf(stderr, "cannot initialise context\n");
		exit(1);
	}

	state = NO_FILE_OPENED;
	while (fz_optind < argc)
	{
		if (strstr(argv[fz_optind], ".pdf") || strstr(argv[fz_optind], ".PDF"))
		{
			if (state == NO_INFO_GATHERED)
			{
				showinfo(filename, show, "1-");
				closexref();
			}

			closexref();

			filename = argv[fz_optind];
			printf("%s:\n", filename);
			xref = pdf_open_document(ctx, filename);
			if (pdf_needs_password(xref))
				if (!pdf_authenticate_password(xref, password))
					fz_throw(ctx, "cannot authenticate password: %s", filename);
			pagecount = pdf_count_pages(xref);

			showglobalinfo();
			state = NO_INFO_GATHERED;
		}
		else
		{
			showinfo(filename, show, argv[fz_optind]);
			state = INFO_SHOWN;
		}

		fz_optind++;
	}

	if (state == NO_INFO_GATHERED)
		showinfo(filename, show, "1-");

	closexref();
	fz_free_context(ctx);
	return 0;
}