The code here builds on the Adding metadata example.
From samples/replace-metadata.c
:
The idea is as follows: we check if there's a metadata entry; if there is, we update it, and if not, we create one and update the root object.
We need two tasks declared for this.
Next, we need to do the actual conditional part in our main()
function.
First case: we have a metadata entry; we plug the updateMetadata
task into the metadata object.
if (metaRef) {
printf("- metadata exists - updating\n");
updateMetadata);
Second case: we do what we did before; create a metadata object, stuff it with stuff, and hook a task up to edit the root object. We're using a different method for creating the object here. You may run into reasons for choosing one over the other one day.
} else {
printf("- metadata missing - adding\n");
char *metaString = "Hello World!";
addMetadata);
}
We then add the task (whichever one it was) and release it (it's retained by the PDPipe).
The task for adding metadata remains the same, which leaves the task for updating it:
{
printf("- performing updateMetadata task\n");
char *metaString = "Hello Again, World!";
}
The resulting file ends up looking like this:
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include "../src/Pajdeg.h"
#include "../src/PDDictionary.h"
#include "../src/PDString.h"
#define die(msg...) do { fprintf(stderr, msg); exit(-1); } while (0)
int main(int argc, char *argv[])
{
if (argc != 3) die("syntax: %s <input PDF file> <output PDF name>\n", argv[0]);
printf("creating pipe\n"
"input : %s\n"
"output : %s\n", argv[1], argv[2]);
if (NULL == pipe) die("failed to create pipe\n");
if (metaRef) {
printf("- metadata exists - updating\n");
updateMetadata);
} else {
printf("- metadata missing - adding\n");
char *metaString = "Hello World!";
addMetadata);
}
printf("- executing pipe\n");
printf("- execution finished (%ld objects processed)\n", obcount);
}
{
printf("- performing addMetadata task\n");
if (PDDictionaryGetEntry(dict, "Metadata")) {
die("error: metadata already exists! code is buggy!\n");
}
PDDictionarySetEntry(dict, "Metadata", meta);
}
{
printf("- performing updateMetadata task\n");
char *metaString = "Hello Again, World!";
}
And this is what it looks like when used:
$ gcc replace-metadata.c -lz ../libpajdeg.a -o replace-metadata
$ ./replace-metadata ../testpdf.pdf out.pdf
creating pipe
input : ../testpdf.pdf
output : out.pdf
- metadata missing - adding
- executing pipe
- performing addMetadata task
- execution finished (20 objects processed)
$ ./replace-metadata out.pdf out2.pdf
creating pipe
input : out.pdf
output : out2.pdf
- metadata exists - updating
- executing pipe
- performing updateMetadata task
- execution finished (21 objects processed)
$ diff -a out.pdf out2.pdf
209c209
< <</Length 12 >>
---
> <</Length 19 >>
211c211
< Hello World!
---
> Hello Again, World!
241c241
< 12497
---
> 12504