create pdf table using libharu
时间: 2023-11-26 15:06:29 浏览: 35
Sure! Here's an example of how you can create a PDF table using the `libharu` library in C++:
```cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hpdf.h>
void error_handler(HPDF_STATUS error_no, HPDF_STATUS detail_no, void *user_data)
{
printf("Error: %04X, detail_no=%d\n", (unsigned int)error_no,
(unsigned int)detail_no);
exit(-1);
}
int main()
{
HPDF_Doc pdf;
HPDF_Page page;
const char *filename = "table_example.pdf";
const char *title = "PDF Table Example";
const int row_count = 5;
const int col_count = 3;
const float margin = 50;
const float table_width = HPDF_GetPageWidth(page) - 2 * margin;
const float table_height = HPDF_GetPageHeight(page) - 2 * margin;
const float cell_width = table_width / col_count;
const float cell_height = 40;
pdf = HPDF_New(error_handler, NULL);
if (!pdf)
{
printf("Error: Failed to create PDF object\n");
return -1;
}
if (setjmp(HPDF_JMP_BUF(pdf)))
{
HPDF_Free(pdf);
return -1;
}
page = HPDF_AddPage(pdf);
HPDF_Page_SetSize(page, HPDF_PAGE_SIZE_A4);
HPDF_Page_SetRGBFill(page, 0, 0, 0);
HPDF_Page_SetRGBStroke(page, 0, 0, 0);
HPDF_Font font = HPDF_GetFont(pdf, "Helvetica", "UTF-8");
HPDF_Page_SetFontAndSize(page, font, 12);
HPDF_Page_BeginText(page);
HPDF_Page_MoveTextPos(page, margin, HPDF_GetPageHeight(page) - margin - 20);
HPDF_Page_ShowText(page, title);
HPDF_Page_EndText(page);
HPDF_Page_SetLineWidth(page, 0.5);
for (int i = 0; i <= row_count; ++i)
{
HPDF_Page_MoveTo(page, margin, HPDF_GetPageHeight(page) - margin - (i + 1) * cell_height);
HPDF_Page_LineTo(page, margin + table_width, HPDF_GetPageHeight(page) - margin - (i + 1) * cell_height);
HPDF_Page_Stroke(page);
}
for (int i = 0; i <= col_count; ++i)
{
HPDF_Page_MoveTo(page, margin + i * cell_width, HPDF_GetPageHeight(page) - margin);
HPDF_Page_LineTo(page, margin + i * cell_width, HPDF_GetPageHeight(page) - margin - table_height);
HPDF_Page_Stroke(page);
}
for (int i = 0; i < row_count; ++i)
{
for (int j = 0; j < col_count; ++j)
{
char cell_text[20];
sprintf(cell_text, "Cell %d-%d", i + 1, j + 1);
HPDF_Page_BeginText(page);
HPDF_Page_MoveTextPos(page, margin + j * cell_width + 2, HPDF_GetPageHeight(page) - margin - (i + 1) * cell_height + 2);
HPDF_Page_ShowText(page, cell_text);
HPDF_Page_EndText(page);
}
}
HPDF_SaveToFile(pdf, filename);
HPDF_Free(pdf);
printf("PDF created successfully!\n");
return 0;
}
```
In this example, we create a PDF document using `HPDF_Doc` and add a new page using `HPDF_AddPage`. We then set the size of the page to A4 using `HPDF_Page_SetSize`. Next, we set the font and size for the text using `HPDF_Page_SetFontAndSize`. We draw the table lines and cell text using `HPDF_Page_MoveTo`, `HPDF_Page_LineTo`, and `HPDF_Page_ShowText`. Finally, we save the PDF to a file using `HPDF_SaveToFile` and free the resources using `HPDF_Free`.
Please note that you need to have `libharu` installed and linked with your project for this code to work.