0

我正在生成一个 pdf 报告,问题是我不知道报告会有多少页,它会有很大的不同。我需要根据需要动态创建页面,我尝试了这个,但它不起作用。

//page counter
int page_num=1;

HPDF_Doc  pdf;
HPDF_Page *page;
char fname[256];
HPDF_Destination dst;
//This works for the first page 
page = malloc(sizeof(*page));
if (page==NULL) {
    printf("Error allocating memory!\n"); //print an error message
} else {
    printf("allocation successful\n");
}

而且我可以正常写入pdf文件,但是当我尝试创建另一个页面时出现分段错误。我试试这样。

page_num ++;
HPDF_Page *temp;
*temp = realloc(page, (page_num+2) * sizeof(page));
if ( temp != NULL ) //realloc was successful
{
page = temp;
page[page_num] = HPDF_AddPage (pdf); //** This line makes it crash **//

printf("Success Reallocating into page\n");
}
else //there was an error
{  printf("Error reallocating into page\n"); }

我正在尝试这样做,因为我需要返回到特定页面并插入带有页码示例“第 1 页,共 50 页”的页脚,如果有其他方法可以做到这一点,请告诉我。在他们的网站上也有一个包含多个页面的示例,但这是在开头设置的一组对我不起作用的页面。

4

2 回答 2

0

*temp = realloc(page, (page_num+2) * sizeof(page)) 此语句错误。page是一个地址点,sizeof(page)是8

于 2014-08-29T01:26:38.063 回答
0

查看类型定义 HPDF_Page
HPDF_Page p;
p 是指针

HPDF_Page *p;
*p 现在是双指针

malloc 内存分配:

HPDF_Page *page; //this is double pointer!!!!

page = malloc(number_of_pages * sizeof(HPDF_Page*)); // memory allocation for array of pointers
if(page) 
{
    for(i = 0; i < number_of_pages; i++)
    {
        page[i] = malloc(sizeof(HPDF_Page)); // allocation for each page pointer
        page[i] = HPDF_AddPage (pdf);
    }
}

Realloc 内存分配:

number_of_pages++;
page = realloc(page, number_of_pages * sizeof(HPDF_Page*)); 

if(page) 
{
        page[number_of_pages-1] = malloc(sizeof(HPDF_Page));
        page[number_of_pages-1] = HPDF_AddPage (pdf);
}


Malloc 将工作。但是 realloc 不起作用,程序会失败!!!我不确定为什么。工作方法是使用链表:

struct my_ch
{
    struct my_ch *n;
    struct my_ch *p;
    HPDF_Page page;
    int page_number;
}*f_item = NULL, *l_item = NULL;

void add_item()
{
    struct my_ch *pom;
    pom = f_item;

    if(pom)
    {
        struct my_ch *prev;

        while(pom->n)
        {
             pom = pom->n;
        }

        prev = pom;
        pom->n = malloc(sizeof(struct my_ch));
        pom = pom->n;
        pom->p = prev;
        pom->n = NULL;
        pom->page = malloc(sizeof(HPDF_Page));
        pom->page_number = pom->prev->page_number + 1;
    }
    else
    {
        pom = malloc(sizeof(struct my_ch));
        pom->p = NULL;
        pom->n = NULL;
        pom->page = malloc(sizeof(HPDF_Page));
        pom->page_number = 1;
    }

    l_item = pom;
}

void add_my_new_page()
{
    add_item();
    l_item->page = HPDF_AddPage(pdf);
    //paste some nice graphic, text...
}

bool modify_page(int number_of_page)
{
    struct my_ch *p;
    p = f_item;

    while(p)
    {
        if(p->page_number == number_of_page)
        {
            // let`s do some modifycation on p->page
            HPDF_Page_Rectangle( p->page, ..., ...);
            HPDF_Page_Stroke(p->page);

            return true;
        }

        p = p->n;
    }

    return false;
}


我在我的程序中使用了这段代码,它运行良好。

于 2017-05-09T07:12:51.547 回答