如何在页面上添加一个文本对象?

如何通过PluginSDK在PDF页面的指定区域添加一个如下图所示的文本对象?

示例代码如下:

  1. 新建一个文本对象

FPD_PageObject CreateTextObj(FPD_Document fpdDoc, FS_LPCWSTR content, int x, int y, FS_FLOAT fontSize)
{
	FPD_PageObject textObj = FPDTextObjectNew();
	FPD_TextState textState = FPDTextStateNew();
	//创建中文宋体
	HFONT hFont = ::CreateFont(12, 0, 0, 0, FW_NORMAL, FALSE, 0, 0, GB2312_CHARSET,
		OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
		DEFAULT_PITCH | FF_DONTCARE, L"SimSun");
	LOGFONTW lf;
	memset(&lf, 0, sizeof(LOGFONTW));

	::GetObject(hFont, sizeof(LOGFONTW), &lf);
	::DeleteObject(hFont);
	FPD_Font font = FPDDocAddWindowsFontW(fpdDoc, &lf, FALSE, FALSE);

	FPDTextStateSetFont(textState, font);
	FPDTextStateSetFontSize(textState, fontSize);
	FPDTextObjectSetTextState(textObj, textState);
	FS_FLOAT	matrix[4]{ 1, 0, 0, 1 };
	FPDTextStateSetMatrix(textState, matrix);
	FPDTextStateDestroy(textState);
	//设置填充色和边框色的颜色空间为RGB
	FPD_ColorState pColorState = FPDColorStateNew();
	if (FPD_Color pFillColor = FPDColorStateGetFillColor(pColorState))
	{
		FPDColorSetColorSpace(pFillColor, FPDColorSpaceGetStockCS(FPD_CS_DEVICERGB));
	}
	if (FPD_Color pStrokeColor = FPDColorStateGetStrokeColor(pColorState))
	{
		FPDColorSetColorSpace(pStrokeColor, FPDColorSpaceGetStockCS(FPD_CS_DEVICERGB));
	}
	//设置颜色
	FS_FLOAT rgb[3];
	rgb[0] = 0.0f;
	rgb[1] = 0.0f;
	rgb[2] = 0.0f;
	FPDColorStateSetFillColor(pColorState, FPDColorSpaceGetStockCS(FPD_CS_DEVICERGB), rgb, 3);
	FPDPageObjectSetColorState(textObj, pColorState);
	FPDColorStateDestroy(pColorState);
	//设置文本的坐标
	FPDTextObjectSetPosition(textObj, x, y);
	int len = lstrlen(content);
	FS_DWORD* pCharCodes = new FS_DWORD[len + 1];
	FS_FLOAT* pKern = new FS_FLOAT[len + 1];
	for (int i = 0; i < len; i++)
	{
		pCharCodes[i] = FPDFontCharCodeFromUnicode(font, content[i]);
		if ((pCharCodes[i] == 0xFFFFFFFF) || (pCharCodes[i] == 0))
		{
			pCharCodes[i] = ' ';
		}
		pKern[i] = 0;
	}
	pCharCodes[len] = 0;
	FPDTextObjectSetText3(textObj, len, pCharCodes, pKern);
	return textObj;
}

2. 将文本对象插入PDF中

FR_Document frDoc = FRAppGetActiveDocOfPDDoc();
FPD_Document fpdDoc= FRDocGetPDDoc(frDoc);
//新建页面
FPD_Object pPageDict = FPDDocCreateNewPage(fpdDoc, 0);
FPD_Page fpdPage = FPDPageNew();
FPDPageLoad(fpdPage, fpdDoc, pPageDict, TRUE);
FS_POSITION pos = FPDPageGetLastObjectPosition(fpdPage);
//新建文本对象
FPD_PageObject textObj = CreateTextObj(fpdDoc, L"欢迎使用Foxit PluginSDK! ", 100, 550, 20);
//插入文本
pos=FPDPageInsertObject(fpdPage, pos, textObj);
//生成正文内容
FPDPageGenerateContent(fpdPage);
FRDocReloadPage(frDoc, 0, FALSE);
return;