Compare commits

..

23 Commits

Author SHA1 Message Date
8550bdeed6 Generate all projects if ommited 2024-10-24 18:05:56 +04:00
5aae57aad8 Log generated project files 2024-10-24 17:43:04 +04:00
1d4f825ea6 Add note to change builder directory for cpp & cs 2024-10-23 13:53:30 +04:00
0527472fef Use space indentation for consistency 2024-10-22 22:00:45 +04:00
c911733bd7 Fix crash on mac 2024-10-22 21:51:21 +04:00
46f254c85d Fix incorrect convertation to string 2024-10-22 20:43:03 +04:00
a6a7d919e6 Add README.md 2024-10-21 16:47:52 +04:00
755d6cd970 Add some Java samples 2024-10-21 15:04:22 +04:00
604dc14d23 Add some python samples 2024-10-18 18:00:54 +04:00
2263d7bf80 Fix Makefile for mac 2024-10-18 14:04:30 +04:00
ef415aad3f Fixes for mac 2024-10-17 18:55:42 +04:00
6744c172f4 Remove C++ compile warnings 2024-10-17 17:43:53 +04:00
6ea3a9551e Add generation of Makefile 2024-10-17 17:35:51 +04:00
f48ab0351c Update help message with C# projects 2024-10-17 15:28:29 +04:00
632ddf9805 Remove asterisks due to portability 2024-10-17 15:22:27 +04:00
2c61e84e94 Fix unresolved symbols on linux 2024-10-17 14:38:21 +04:00
375b37e9aa Add include paths for utils 2024-10-16 19:07:29 +04:00
bb3e2e3bc2 Fix issue with relative paths to resources 2024-10-16 18:20:04 +04:00
1a5b8b4bbd Add generation of Qt C++ projects 2024-10-16 18:17:40 +04:00
901c44b486 Add generation of VS .NET projects 2024-10-15 19:00:29 +04:00
88eadd9955 Add remaining C++ samples 2024-10-15 16:04:23 +04:00
b5f88cebaf Fix C++ projects for old VS versions
+ Add spreadsheet test
2024-10-15 14:52:14 +04:00
e0e7e31568 Add generation of VS C++ projects 2024-10-14 20:18:57 +04:00
188 changed files with 5221 additions and 3354 deletions

View File

@ -259,17 +259,20 @@ buildBoost()
echo Building Boost for iPhone
# Install this one so we can copy the headers for the frameworks...
./b2 -j16 --build-dir=iphone-build --stagedir=iphone-build/stage \
cxxflags="" \
--prefix=$PREFIXDIR toolset=darwin architecture=arm target-os=iphone \
macosx-version=iphone-${IOS_SDK_VERSION} define=_LITTLE_ENDIAN \
link=static stage
./b2 -j16 --build-dir=iphone-build --stagedir=iphone-build/stage \
--prefix=$PREFIXDIR toolset=darwin architecture=arm \
cxxflags="" \
target-os=iphone macosx-version=iphone-${IOS_SDK_VERSION} \
define=_LITTLE_ENDIAN link=static install
doneSection
echo Building Boost for iPhoneSimulator
./b2 -j16 --build-dir=iphonesim-build --stagedir=iphonesim-build/stage \
cxxflags="" \
toolset=darwin-${IOS_SDK_VERSION}~iphonesim architecture=x86 \
target-os=iphone macosx-version=iphonesim-${IOS_SDK_VERSION} \
link=static stage

View File

@ -18,12 +18,12 @@ namespace NSCSS
{
typedef std::map<std::wstring, std::wstring>::const_iterator styles_iterator;
CCompiledStyle::CCompiledStyle() : m_nDpi(96), m_UnitMeasure(Point), m_dCoreFontSize(DEFAULT_FONT_SIZE)
CCompiledStyle::CCompiledStyle() : m_nDpi(96), m_UnitMeasure(Point)
{}
CCompiledStyle::CCompiledStyle(const CCompiledStyle& oStyle) :
m_arParentsStyles(oStyle.m_arParentsStyles), m_sId(oStyle.m_sId),
m_nDpi(oStyle.m_nDpi), m_UnitMeasure(oStyle.m_UnitMeasure), m_dCoreFontSize(oStyle.m_dCoreFontSize),
m_nDpi(oStyle.m_nDpi), m_UnitMeasure(oStyle.m_UnitMeasure),
m_oFont(oStyle.m_oFont), m_oMargin(oStyle.m_oMargin), m_oPadding(oStyle.m_oPadding), m_oBackground(oStyle.m_oBackground),
m_oText(oStyle.m_oText), m_oBorder(oStyle.m_oBorder), m_oDisplay(oStyle.m_oDisplay){}
@ -116,10 +116,7 @@ namespace NSCSS
void CCompiledStyle::AddStyle(const std::map<std::wstring, std::wstring>& mStyle, const unsigned int unLevel, const bool& bHardMode)
{
const bool bIsThereBorder = (m_oBorder.Empty()) ? false : true;
const double dParentFontSize = (!m_oFont.GetSize().Empty()) ? m_oFont.GetSize().ToDouble(NSCSS::Point) : DEFAULT_FONT_SIZE;
if (0 == unLevel)
m_dCoreFontSize = dParentFontSize;
const double dFontSize = (!m_oFont.GetSize().Empty()) ? m_oFont.GetSize().ToDouble(NSCSS::Point) : DEFAULT_FONT_SIZE;
for (std::pair<std::wstring, std::wstring> pPropertie : mStyle)
{
@ -131,15 +128,15 @@ namespace NSCSS
CASE(L"font"):
{
m_oFont.SetValue(pPropertie.second, unLevel, bHardMode);
m_oFont.UpdateSize(dParentFontSize, m_dCoreFontSize);
m_oFont.UpdateLineHeight(dParentFontSize, m_dCoreFontSize);
m_oFont.UpdateSize(dFontSize);
m_oFont.UpdateLineHeight(dFontSize);
break;
}
CASE(L"font-size"):
CASE(L"font-size-adjust"):
{
m_oFont.SetSize(pPropertie.second, unLevel, bHardMode);
m_oFont.UpdateSize(dParentFontSize, m_dCoreFontSize);
m_oFont.UpdateSize(dFontSize);
break;
}
CASE(L"font-stretch"):
@ -179,7 +176,7 @@ namespace NSCSS
break;
m_oMargin.SetValues(pPropertie.second, unLevel, bHardMode);
m_oMargin.UpdateAll(dParentFontSize, m_dCoreFontSize);
m_oMargin.UpdateAll(dFontSize);
break;
}
CASE(L"margin-top"):
@ -199,7 +196,7 @@ namespace NSCSS
break;
m_oMargin.SetRight(pPropertie.second, unLevel, bHardMode);
m_oMargin.UpdateRight(dParentFontSize, m_dCoreFontSize);
m_oMargin.UpdateRight(dFontSize);
break;
}
CASE(L"margin-bottom"):
@ -209,7 +206,7 @@ namespace NSCSS
break;
m_oMargin.SetBottom(pPropertie.second, unLevel, bHardMode);
m_oMargin.UpdateBottom(dParentFontSize, m_dCoreFontSize);
m_oMargin.UpdateBottom(dFontSize);
break;
}
CASE(L"margin-left"):
@ -220,7 +217,7 @@ namespace NSCSS
break;
m_oMargin.SetLeft(pPropertie.second, unLevel, bHardMode);
m_oMargin.UpdateLeft(dParentFontSize, m_dCoreFontSize);
m_oMargin.UpdateLeft(dFontSize);
break;
}
//PADDING
@ -228,35 +225,35 @@ namespace NSCSS
CASE(L"mso-padding-alt"):
{
m_oPadding.SetValues(pPropertie.second, unLevel, bHardMode);
m_oPadding.UpdateAll(dParentFontSize, m_dCoreFontSize);
m_oPadding.UpdateAll(dFontSize);
break;
}
CASE(L"padding-top"):
CASE(L"mso-padding-top-alt"):
{
m_oPadding.SetTop(pPropertie.second, unLevel, bHardMode);
m_oPadding.UpdateTop(dParentFontSize, m_dCoreFontSize);
m_oPadding.UpdateTop(dFontSize);
break;
}
CASE(L"padding-right"):
CASE(L"mso-padding-right-alt"):
{
m_oPadding.SetRight(pPropertie.second, unLevel, bHardMode);
m_oPadding.UpdateRight(dParentFontSize, m_dCoreFontSize);
m_oPadding.UpdateRight(dFontSize);
break;
}
CASE(L"padding-bottom"):
CASE(L"mso-padding-bottom-alt"):
{
m_oPadding.SetBottom(pPropertie.second, unLevel, bHardMode);
m_oPadding.UpdateBottom(dParentFontSize, m_dCoreFontSize);
m_oPadding.UpdateBottom(dFontSize);
break;
}
CASE(L"padding-left"):
CASE(L"mso-padding-left-alt"):
{
m_oPadding.SetLeft(pPropertie.second, unLevel, bHardMode);
m_oPadding.UpdateLeft(dParentFontSize, m_dCoreFontSize);
m_oPadding.UpdateLeft(dFontSize);
break;
}
// TEXT

View File

@ -22,7 +22,6 @@ namespace NSCSS
unsigned short int m_nDpi;
UnitMeasure m_UnitMeasure;
double m_dCoreFontSize;
public:
NSProperties::CFont m_oFont;
NSProperties::CIndent m_oMargin;

View File

@ -2301,32 +2301,32 @@ namespace NSCSS
return m_oLeft.SetValue(dValue, unLevel, bHardMode);
}
void CIndent::UpdateAll(const double& dParentFontSize, const double& dCoreFontSize)
void CIndent::UpdateAll(double dFontSize)
{
UpdateTop (dParentFontSize, dCoreFontSize);
UpdateRight (dParentFontSize, dCoreFontSize);
UpdateBottom(dParentFontSize, dCoreFontSize);
UpdateLeft (dParentFontSize, dCoreFontSize);
UpdateTop (dFontSize);
UpdateRight (dFontSize);
UpdateBottom(dFontSize);
UpdateLeft (dFontSize);
}
void CIndent::UpdateTop(const double& dParentFontSize, const double& dCoreFontSize)
void CIndent::UpdateTop(double dFontSize)
{
UpdateSide(m_oTop, dParentFontSize, dCoreFontSize);
UpdateSide(m_oTop, dFontSize);
}
void CIndent::UpdateRight(const double& dParentFontSize, const double& dCoreFontSize)
void CIndent::UpdateRight(double dFontSize)
{
UpdateSide(m_oRight, dParentFontSize, dCoreFontSize);
UpdateSide(m_oRight, dFontSize);
}
void CIndent::UpdateBottom(const double& dParentFontSize, const double& dCoreFontSize)
void CIndent::UpdateBottom(double dFontSize)
{
UpdateSide(m_oBottom, dParentFontSize, dCoreFontSize);
UpdateSide(m_oBottom, dFontSize);
}
void CIndent::UpdateLeft(const double& dParentFontSize, const double& dCoreFontSize)
void CIndent::UpdateLeft(double dFontSize)
{
UpdateSide(m_oLeft, dParentFontSize, dCoreFontSize);
UpdateSide(m_oLeft, dFontSize);
}
const CDigit &CIndent::GetTop() const
@ -2395,15 +2395,13 @@ namespace NSCSS
return bTopResult || bRightResult || bBottomResult || bLeftResult;
}
void CIndent::UpdateSide(CDigit &oSide, const double& dParentFontSize, const double& dCoreFontSize)
void CIndent::UpdateSide(CDigit &oSide, double dFontSize)
{
if (oSide.Empty())
return;
if (NSCSS::Em == oSide.GetUnitMeasure())
oSide.ConvertTo(NSCSS::Twips, dParentFontSize);
else if (NSCSS::Rem == oSide.GetUnitMeasure())
oSide.ConvertTo(NSCSS::Twips, dCoreFontSize);
if (NSCSS::Em == oSide.GetUnitMeasure() || NSCSS::Rem == oSide.GetUnitMeasure())
oSide.ConvertTo(NSCSS::Twips, dFontSize);
}
// FONT
@ -2646,20 +2644,16 @@ namespace NSCSS
std::make_pair(L"700", L"bold"), std::make_pair(L"800", L"bold"), std::make_pair(L"900", L"bold")}, unLevel, bHardMode);
}
void CFont::UpdateSize(const double& dParentFontSize, const double& dCoreFontSize)
void CFont::UpdateSize(double dFontSize)
{
if (NSCSS::Em == m_oSize.GetUnitMeasure() || NSCSS::Percent == m_oSize.GetUnitMeasure())
m_oSize.ConvertTo(NSCSS::Point, dParentFontSize);
else if (NSCSS::Rem == m_oSize.GetUnitMeasure())
m_oSize.ConvertTo(NSCSS::Point, dCoreFontSize);
if (NSCSS::Em == m_oSize.GetUnitMeasure() || NSCSS::Rem == m_oSize.GetUnitMeasure() || NSCSS::Percent == m_oSize.GetUnitMeasure())
m_oSize.ConvertTo(NSCSS::Point, dFontSize);
}
void CFont::UpdateLineHeight(const double& dParentFontSize, const double& dCoreFontSize)
void CFont::UpdateLineHeight(double dFontSize)
{
if (NSCSS::Em == m_oLineHeight.GetUnitMeasure())
m_oLineHeight.ConvertTo(NSCSS::Twips, dParentFontSize);
else if (NSCSS::Rem == m_oLineHeight.GetUnitMeasure())
m_oLineHeight.ConvertTo(NSCSS::Twips, dCoreFontSize);
if (NSCSS::Em == m_oLineHeight.GetUnitMeasure() || NSCSS::Rem == m_oLineHeight.GetUnitMeasure())
m_oLineHeight.ConvertTo(NSCSS::Twips, dFontSize);
}
bool CFont::Bold() const

View File

@ -656,11 +656,11 @@ namespace NSCSS
bool SetLeft (const std::wstring& wsValue, unsigned int unLevel, bool bHardMode = false);
bool SetLeft (const double& dValue, unsigned int unLevel, bool bHardMode = false);
void UpdateAll (const double& dParentFontSize, const double& dCoreFontSize);
void UpdateTop (const double& dParentFontSize, const double& dCoreFontSize);
void UpdateRight (const double& dParentFontSize, const double& dCoreFontSize);
void UpdateBottom(const double& dParentFontSize, const double& dCoreFontSize);
void UpdateLeft (const double& dParentFontSize, const double& dCoreFontSize);
void UpdateAll (double dFontSize);
void UpdateTop (double dFontSize);
void UpdateRight (double dFontSize);
void UpdateBottom(double dFontSize);
void UpdateLeft (double dFontSize);
const CDigit& GetTop () const;
const CDigit& GetRight () const;
@ -675,7 +675,7 @@ namespace NSCSS
bool operator!=(const CIndent& oIndent) const;
private:
bool SetValues(const std::wstring& wsTopValue, const std::wstring& wsRightValue, const std::wstring& wsBottomValue, const std::wstring& wsLeftValue, unsigned int unLevel, bool bHardMode = false);
void UpdateSide(CDigit& oSide, const double& dParentFontSize, const double& dCoreFontSize);
void UpdateSide(CDigit& oSide, double dFontSize);
CDigit m_oLeft;
CDigit m_oTop;
@ -702,8 +702,8 @@ namespace NSCSS
bool SetVariant (const std::wstring& wsValue, unsigned int unLevel, bool bHardMode = false);
bool SetWeight (const std::wstring& wsValue, unsigned int unLevel, bool bHardMode = false);
void UpdateSize(const double& dParentFontSize, const double& dCoreFontSize);
void UpdateLineHeight(const double& dParentFontSize, const double& dCoreFontSize);
void UpdateSize(double dFontSize);
void UpdateLineHeight(double dFontSize);
void Clear();

View File

@ -55,11 +55,6 @@ static void replace_all(std::string& s, const std::string& s1, const std::string
}
}
static bool NodeIsUnprocessed(const std::string& wsTagName)
{
return "xml" == wsTagName;
}
static bool IsUnckeckedNodes(const std::string& sValue)
{
return unchecked_nodes_new.end() != std::find(unchecked_nodes_new.begin(), unchecked_nodes_new.end(), sValue);
@ -597,9 +592,6 @@ static void prettyprint(GumboNode* node, NSStringUtils::CStringBuilderA& oBuilde
std::string tagname = get_tag_name(node);
if (NodeIsUnprocessed(tagname))
return;
if (bCheckValidNode)
bCheckValidNode = !IsUnckeckedNodes(tagname);

View File

@ -847,10 +847,40 @@ namespace agg
if (calculate_tensor_coefs)
calculate_tensor();
float minxres = m_oGradientInfo.shading.patch[0][0].x;
float minyres = m_oGradientInfo.shading.patch[0][0].y;
float maxxres = m_oGradientInfo.shading.patch[0][0].x;
float maxyres = m_oGradientInfo.shading.patch[0][0].y;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (m_oGradientInfo.shading.patch[i][j].x > maxxres)
{
maxxres = m_oGradientInfo.shading.patch[i][j].x;
}
if (m_oGradientInfo.shading.patch[i][j].y > maxyres)
{
maxyres = m_oGradientInfo.shading.patch[i][j].y;
}
if (m_oGradientInfo.shading.patch[i][j].x < minxres)
{
minxres = m_oGradientInfo.shading.patch[i][j].x;
}
if (m_oGradientInfo.shading.patch[i][j].y < minyres)
{
minyres = m_oGradientInfo.shading.patch[i][j].y;
}
}
}
RES = std::max(1.0f, std::max(maxxres - minxres, maxyres - minyres) / 3);
float delta = 1.0 / RES;
float u = 0, v = 0;
auto start_p = get_p_curve(u, v);
xmax_curve = xmin_curve = start_p.x;
ymax_curve = ymin_curve = start_p.y;
precalc = std::vector<std::vector<ColorT>>(RES, std::vector<ColorT>(RES, {0, 0, 0, 0}));
/*
* Небольшая оптимизация основанная на том, что данная фигура не выходит за границы своих опорных точек.
@ -888,7 +918,7 @@ namespace agg
RES = nRES;
}
precalc = std::vector<std::vector<ColorT>>(RES, std::vector<ColorT>(RES, {0, 0, 0, 0}));
float delta = 1.0f / RES;
delta = 1.0f / RES;
std::vector<std::pair<int, int>> next_indexes(RES + 1);
u = 0;
for (int i = 0; i < RES; ++i)
@ -926,6 +956,8 @@ namespace agg
}
ColorT ifswapRGB(const ColorT &c)
{
if (m_bSwapRGB) {
return c;
}

View File

@ -250,123 +250,3 @@ namespace NSBase64
return Base64DecodeBase(szSrc, nSrcLen, pbDest, pnDestLen);
}
}
#include <cstring>
namespace NSBase32
{
const unsigned char PADDING_CHAR_32 = '=';
inline void pad(unsigned char* buf, int len)
{
for (int i = 0; i < len; i++)
buf[i] = PADDING_CHAR_32;
}
inline unsigned char shift_right(unsigned char byte, signed char offset)
{
if (offset > 0)
return byte >> offset;
else
return byte << -offset;
}
inline unsigned char shift_left(unsigned char byte, signed char offset)
{
return shift_right(byte, - offset);
}
unsigned char encode_char(unsigned char c)
{
static unsigned char base32[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
return base32[c & 0x1F];
}
int decode_char(unsigned char c)
{
char retval = -2;
if (c >= 'A' && c <= 'Z')
retval = c - 'A';
else if (c >= '2' && c <= '7')
retval = c - '2' + 26;
else if (c == PADDING_CHAR_32)
retval = -1;
return retval;
}
int decode_sequence(const unsigned char* coded, unsigned char* plain)
{
plain[0] = 0;
for (int block = 0; block < 8; block++)
{
int offset = (8 - 5 - (5*block) % 8);
int octet = (block*5) / 8;
int c = decode_char(coded[block]);
if (c < 0)
return c;
plain[octet] |= shift_left(c, offset);
if (offset < 0)
{ // does this block overflows to next octet?
plain[octet+1] = shift_left(c, 8 + offset);
}
}
return 5;
}
bool Decode(unsigned char* in, int inLen, unsigned char* out)
{
for (size_t i = 0, j = 0; (i + 8) <= inLen; i += 8, j += 5)
{
int n = decode_sequence(&in[i], &out[j]);
if (n == -2)
return false;
if (n < 5)
break;
}
return true;
}
void encode_sequence(const unsigned char* plain, int len, unsigned char* coded)
{
for (int block = 0; block < 8; block++)
{
int octet = (block*5) / 8;
int junk = (8 - 5 - (5*block) % 8);
if (octet >= len)
{
pad(&coded[block], 8 - block);
return;
}
unsigned char c = shift_right(plain[octet], junk); // first part
if (junk < 0 // is there a second part?
&& octet < len - 1) // is there still something to read?
{
c |= shift_right(plain[octet+1], 8 + junk);
}
coded[block] = encode_char(c);
}
}
bool Encode(unsigned char* src, int len, unsigned char* dst)
{
for (int i = 0, j = 0; i < len; i += 5, j += 8)
{
int tmpLen = len - i;
encode_sequence(&src[i], tmpLen > 5 ? 5 : tmpLen, &dst[j]);
}
return true;
}
int DecodeGetRequiredLength(int bytes)
{
return (((bytes)/8)*5);
}
int EncodeGetRequiredLength(int bytes)
{
return (((bytes)/5)*8 + ((bytes) % 5 ? 8 : 0));
}
}

View File

@ -58,13 +58,4 @@ namespace NSBase64
KERNEL_DECL int Base64Decode(const wchar_t* szSrc, int nSrcLen, BYTE *pbDest, int *pnDestLen);
}
namespace NSBase32
{
KERNEL_DECL bool Decode(unsigned char* in, int inLen, unsigned char* out);
KERNEL_DECL bool Encode(unsigned char* in, int inLen, unsigned char* out);
KERNEL_DECL int DecodeGetRequiredLength(int bytes);
KERNEL_DECL int EncodeGetRequiredLength(int bytes);
}
#endif//_BUILD_BASE64_CROSSPLATFORM_DEFINE

View File

@ -1535,11 +1535,6 @@ namespace NSFile
return bIsSuccess;
}
bool CFileBinary::IsGlobalTempPathUse()
{
return g_overrideTmpPath.empty() ? false : true;
}
std::wstring CFileBinary::GetTempPath()
{
if (!g_overrideTmpPath.empty())

View File

@ -189,7 +189,6 @@ namespace NSFile
static void SetTempPath(const std::wstring& strTempPath);
static std::wstring GetTempPath();
static bool IsGlobalTempPathUse();
static std::wstring CreateTempFileWithUniqueName(const std::wstring& strFolderPathRoot, const std::wstring& Prefix);
static bool OpenTempFile(std::wstring *pwsName, FILE **ppFile, wchar_t *wsMode, wchar_t *wsExt, wchar_t *wsFolder, wchar_t* wsName = NULL);

View File

@ -682,10 +682,9 @@ namespace NSStringUtils
}
if (val < 0)
{
if (val == -2147483648)
val = -val;
if (val < 0)
val = 2147483647;
else
val = -val;
*m_pDataCur++ = (wchar_t)'-';
++m_lSizeCur;

View File

@ -56,6 +56,7 @@ CV8RealTimeWorker::CV8RealTimeWorker(NSDoctRenderer::CDocBuilder* pBuilder, cons
CJSContextScope scope(m_context);
CJSContext::Embed<CNativeControlEmbed>(false);
CJSContext::Embed<CGraphicsEmbed>();
NSJSBase::CreateDefaults();
JSSmart<CJSTryCatch> try_catch = m_context->GetExceptions();

View File

@ -728,13 +728,22 @@ namespace NSDoctRenderer
oBuilder.WriteEncodeXmlString(sFolder);
oBuilder.WriteString(L"/Editor.bin</m_sFileTo><m_nFormatTo>8192</m_nFormatTo>");
oBuilder.WriteString(L"<m_sFontDir>");
oBuilder.WriteEncodeXmlString(NSFile::GetDirectoryName(m_strAllFonts));
oBuilder.WriteString(L"</m_sFontDir>");
if (!m_bIsNotUseConfigAllFontsDir)
{
oBuilder.WriteString(L"<m_sFontDir>");
oBuilder.WriteEncodeXmlString(m_sX2tPath + L"/sdkjs/common");
oBuilder.WriteString(L"</m_sFontDir>");
}
else
{
oBuilder.WriteString(L"<m_sFontDir>");
oBuilder.WriteEncodeXmlString(NSFile::GetDirectoryName(m_strAllFonts));
oBuilder.WriteString(L"</m_sFontDir>");
oBuilder.WriteString(L"<m_sAllFontsPath>");
oBuilder.WriteEncodeXmlString(m_strAllFonts);
oBuilder.WriteString(L"</m_sAllFontsPath>");
oBuilder.WriteString(L"<m_sAllFontsPath>");
oBuilder.WriteEncodeXmlString(m_strAllFonts);
oBuilder.WriteString(L"</m_sAllFontsPath>");
}
oBuilder.WriteString(L"<m_bIsNoBase64>true</m_bIsNoBase64>");
oBuilder.WriteString(L"<m_sThemeDir>./sdkjs/slide/themes</m_sThemeDir><m_bDontSaveAdditional>true</m_bDontSaveAdditional>");
@ -1045,13 +1054,22 @@ namespace NSDoctRenderer
oBuilder.WriteString(L"</m_sThemeDir><m_bFromChanges>true</m_bFromChanges><m_bDontSaveAdditional>true</m_bDontSaveAdditional>");
oBuilder.WriteString(L"<m_nCsvTxtEncoding>46</m_nCsvTxtEncoding><m_nCsvDelimiter>4</m_nCsvDelimiter>");
oBuilder.WriteString(L"<m_sFontDir>");
oBuilder.WriteEncodeXmlString(NSFile::GetDirectoryName(m_strAllFonts));
oBuilder.WriteString(L"</m_sFontDir>");
if (!m_bIsNotUseConfigAllFontsDir)
{
oBuilder.WriteString(L"<m_sFontDir>");
oBuilder.WriteEncodeXmlString(m_sX2tPath + L"/sdkjs/common");
oBuilder.WriteString(L"</m_sFontDir>");
}
else
{
oBuilder.WriteString(L"<m_sFontDir>");
oBuilder.WriteEncodeXmlString(NSFile::GetDirectoryName(m_strAllFonts));
oBuilder.WriteString(L"</m_sFontDir>");
oBuilder.WriteString(L"<m_sAllFontsPath>");
oBuilder.WriteEncodeXmlString(m_strAllFonts);
oBuilder.WriteString(L"</m_sAllFontsPath>");
oBuilder.WriteString(L"<m_sAllFontsPath>");
oBuilder.WriteEncodeXmlString(m_strAllFonts);
oBuilder.WriteString(L"</m_sAllFontsPath>");
}
if (!sConvertionParams.empty())
{

View File

@ -575,6 +575,7 @@ namespace NSDoctRenderer
{
CJSContextScope scope(context);
CJSContext::Embed<CNativeControlEmbed>(false);
CJSContext::Embed<CGraphicsEmbed>();
NSJSBase::CreateDefaults();
JSSmart<CJSTryCatch> try_catch = context->GetExceptions();
@ -1066,6 +1067,7 @@ namespace NSDoctRenderer
{
CJSContextScope scope(context);
CJSContext::Embed<CNativeControlEmbed>();
CJSContext::Embed<CGraphicsEmbed>();
NSJSBase::CreateDefaults();
JSSmart<CJSObject> global = context->GetGlobal();

View File

@ -4,7 +4,6 @@
#include "./MemoryStreamEmbed.h"
#include "./TextMeasurerEmbed.h"
#include "./HashEmbed.h"
#include "./GraphicsEmbed.h"
namespace NSJSBase
{
@ -14,6 +13,5 @@ namespace NSJSBase
CJSContext::Embed<CMemoryStreamEmbed>();
CJSContext::Embed<CTextMeasurerEmbed>();
CJSContext::Embed<CHashEmbed>();
CJSContext::Embed<CGraphicsEmbed>();
}
}

View File

@ -1,178 +1,8 @@
#include "../graphics.h"
#include <map>
#include "../../../Common/Network/FileTransporter/include/FileTransporter.h"
// APPLICATION INFO
class CGraphicsAppImage_private
{
public:
NSFonts::IApplicationFonts* m_pFonts;
std::wstring m_sFontsDirectory;
std::wstring m_sImagesDirectory;
std::wstring m_sThemesDirectory;
bool m_bIsRgba;
std::map<std::wstring, std::wstring> m_mapDownloads;
CGraphicsAppImage_private()
{
m_pFonts = NULL;
m_sFontsDirectory = L"";
m_sImagesDirectory = L"";
m_sThemesDirectory = L"";
m_bIsRgba = false;
}
~CGraphicsAppImage_private()
{
RELEASEINTERFACE(m_pFonts);
for (std::map<std::wstring, std::wstring>::iterator i = m_mapDownloads.begin(); i != m_mapDownloads.end(); i++)
{
std::wstring sTmp = i->second;
if (NSFile::CFileBinary::Exists(sTmp))
NSFile::CFileBinary::Remove(sTmp);
}
}
bool IsNeedDownload(const std::wstring& sUrl)
{
if ((0 == sUrl.find(L"www.")) ||
(0 == sUrl.find(L"http://")) ||
(0 == sUrl.find(L"https://")))
return true;
return false;
}
std::wstring GetImagePath(const std::wstring& sUrl)
{
std::map<std::wstring, std::wstring>::iterator find = m_mapDownloads.find(sUrl);
if (find != m_mapDownloads.end())
return find->second;
NSNetwork::NSFileTransport::CFileDownloader oDownloader(sUrl, false);
std::wstring sTmpFile = NSFile::CFileBinary::CreateTempFileWithUniqueName(NSFile::CFileBinary::GetTempPath(), L"IMG");
if (NSFile::CFileBinary::Exists(sTmpFile))
NSFile::CFileBinary::Remove(sTmpFile);
sTmpFile = sTmpFile + L".png";
oDownloader.SetFilePath(sTmpFile);
oDownloader.Start(0);
while ( oDownloader.IsRunned() )
{
NSThreads::Sleep( 10 );
}
bool bIsDownloaded = oDownloader.IsFileDownloaded();
if (bIsDownloaded)
{
m_mapDownloads.insert(std::pair<std::wstring, std::wstring>(sUrl, sTmpFile));
return sTmpFile;
}
return sUrl;
}
};
CGraphicsAppImage::CGraphicsAppImage()
{
m_internal = new CGraphicsAppImage_private();
}
CGraphicsAppImage::~CGraphicsAppImage()
{
delete m_internal;
}
void CGraphicsAppImage::SetFontsDirectory(const std::wstring& dir)
{
m_internal->m_sFontsDirectory = dir;
}
std::wstring CGraphicsAppImage::GetFontsDirectory()
{
return m_internal->m_sFontsDirectory;
}
void CGraphicsAppImage::SetImagesDirectory(const std::wstring& dir)
{
m_internal->m_sImagesDirectory = dir;
}
std::wstring CGraphicsAppImage::GetImagesDirectory()
{
return m_internal->m_sImagesDirectory;
}
void CGraphicsAppImage::SetThemesDirectory(const std::wstring& dir)
{
m_internal->m_sThemesDirectory = dir;
}
std::wstring CGraphicsAppImage::GetThemesDirectory()
{
return m_internal->m_sThemesDirectory;
}
void CGraphicsAppImage::SetFonts(NSFonts::IApplicationFonts* fonts)
{
m_internal->m_pFonts = fonts;
ADDREFINTERFACE(fonts);
}
NSFonts::IApplicationFonts* CGraphicsAppImage::GetFonts()
{
return m_internal->m_pFonts;
}
void CGraphicsAppImage::SetRgba(const bool& isRgba)
{
m_internal->m_bIsRgba = isRgba;
}
bool CGraphicsAppImage::GetRgba()
{
return m_internal->m_bIsRgba;
}
unsigned char* CGraphicsAppImage::GetBits(int& w, int& h)
{
return NULL;
}
unsigned char* CGraphicsAppImage::AllocBits(const int& w, const int& h)
{
return new unsigned char[4 * w * h];
}
// APPLICATION INFO END
CGraphicsEmbed::CGraphicsEmbed() : m_pInternal(new NSGraphics::CGraphics())
{
}
CGraphicsEmbed::~CGraphicsEmbed()
{
RELEASEOBJECT(m_pInternal);
}
CGraphicsAppImage* CGraphicsEmbed::GetAppImage()
{
return m_pInternal->m_pAppImage;
}
void CGraphicsEmbed::SetAppImage(CGraphicsAppImage* appImage)
{
m_pInternal->m_pAppImage = appImage;
}
#include "GraphicsEmbed.h"
JSSmart<CJSValue> CGraphicsEmbed::create(JSSmart<CJSValue> Native, JSSmart<CJSValue> width_px, JSSmart<CJSValue> height_px, JSSmart<CJSValue> width_mm, JSSmart<CJSValue> height_mm)
{
NSNativeControl::CNativeControl* pControl = NULL;
if (!Native->isNull())
{
pControl = (NSNativeControl::CNativeControl*)Native->toObject()->getNative()->getObject();
if (m_pInternal->m_pAppImage)
delete m_pInternal->m_pAppImage;
m_pInternal->m_pAppImage = new CGraphicsAppImage();
m_pInternal->m_pAppImage->SetFontsDirectory(pControl->m_strFontsDirectory);
m_pInternal->m_pAppImage->SetImagesDirectory(pControl->m_strImagesDirectory);
}
m_pInternal->init(width_px->toDouble(), height_px->toDouble(), width_mm->toDouble(), height_mm->toDouble());
m_pInternal->init((NSNativeControl::CNativeControl*)Native->toObject()->getNative()->getObject(), width_px->toDouble(), height_px->toDouble(), width_mm->toDouble(), height_mm->toDouble());
return NULL;
}
JSSmart<CJSValue> CGraphicsEmbed::Destroy()
@ -320,19 +150,11 @@ JSSmart<CJSValue> CGraphicsEmbed::ClearLastFont()
}
JSSmart<CJSValue> CGraphicsEmbed::drawImage2(JSSmart<CJSValue> img, JSSmart<CJSValue> x, JSSmart<CJSValue> y, JSSmart<CJSValue> w, JSSmart<CJSValue> h, JSSmart<CJSValue> alpha, JSSmart<CJSValue> srcRect)
{
std::wstring sUrl = img->toStringW();
if (m_pInternal->m_pAppImage && m_pInternal->m_pAppImage->m_internal->IsNeedDownload(sUrl))
sUrl = m_pInternal->m_pAppImage->m_internal->GetImagePath(sUrl);
m_pInternal->drawImage(sUrl, x->toDouble(), y->toDouble(), w->toDouble(), h->toDouble(), alpha->toInt32());
m_pInternal->drawImage(img->toStringW(), x->toDouble(), y->toDouble(), w->toDouble(), h->toDouble(), alpha->toInt32());
return NULL;
}
JSSmart<CJSValue> CGraphicsEmbed::drawImage (JSSmart<CJSValue> img, JSSmart<CJSValue> x, JSSmart<CJSValue> y, JSSmart<CJSValue> w, JSSmart<CJSValue> h, JSSmart<CJSValue> alpha, JSSmart<CJSValue> srcRect, JSSmart<CJSValue> nativeImage)
{
std::wstring sUrl = img->toStringW();
if (m_pInternal->m_pAppImage && m_pInternal->m_pAppImage->m_internal->IsNeedDownload(sUrl))
sUrl = m_pInternal->m_pAppImage->m_internal->GetImagePath(sUrl);
m_pInternal->drawImage(img->toStringW(), x->toDouble(), y->toDouble(), w->toDouble(), h->toDouble(), alpha->toInt32());
return NULL;
}
@ -637,11 +459,7 @@ JSSmart<CJSValue> CGraphicsEmbed::GetBrushColor()
}
JSSmart<CJSValue> CGraphicsEmbed::put_brushTexture(JSSmart<CJSValue> src, JSSmart<CJSValue> type)
{
std::wstring sUrl = src->toStringW();
if (m_pInternal->m_pAppImage && m_pInternal->m_pAppImage->m_internal->IsNeedDownload(sUrl))
sUrl = m_pInternal->m_pAppImage->m_internal->GetImagePath(sUrl);
m_pInternal->put_brushTexture(sUrl, type->toInt32());
m_pInternal->put_brushTexture(src->toStringW(), type->toInt32());
return NULL;
}
JSSmart<CJSValue> CGraphicsEmbed::put_brushTextureMode(JSSmart<CJSValue> mode)

View File

@ -1,57 +1,21 @@
#ifndef _BUILD_NATIVE_GRAPHICS_EMBED_H_
#define _BUILD_NATIVE_GRAPHICS_EMBED_H_
#include "../../graphics/pro/Fonts.h"
#include "../graphics.h"
#include "../js_internal/js_base.h"
class CGraphicsAppImage_private;
class JS_DECL CGraphicsAppImage
{
public:
CGraphicsAppImage();
virtual ~CGraphicsAppImage();
public:
void SetFontsDirectory(const std::wstring& dir);
std::wstring GetFontsDirectory();
void SetImagesDirectory(const std::wstring& dir);
std::wstring GetImagesDirectory();
void SetThemesDirectory(const std::wstring& dir);
std::wstring GetThemesDirectory();
void SetFonts(NSFonts::IApplicationFonts* fonts);
NSFonts::IApplicationFonts* GetFonts();
void SetRgba(const bool& isRgba);
bool GetRgba();
virtual unsigned char* GetBits(int& w, int& h);
virtual unsigned char* AllocBits(const int& w, const int& h);
private:
CGraphicsAppImage_private* m_internal;
friend class CGraphicsEmbed;
};
namespace NSGraphics { class CGraphics; }
using namespace NSJSBase;
class JS_DECL CGraphicsEmbed : public CJSEmbedObject
class CGraphicsEmbed : public CJSEmbedObject
{
public:
NSGraphics::CGraphics* m_pInternal;
public:
CGraphicsEmbed();
~CGraphicsEmbed();
CGraphicsEmbed() : m_pInternal(new NSGraphics::CGraphics()) {}
~CGraphicsEmbed() { RELEASEOBJECT(m_pInternal); }
virtual void* getObject() override { return (void*)m_pInternal; }
CGraphicsAppImage* GetAppImage();
void SetAppImage(CGraphicsAppImage* appImage);
public:
JSSmart<CJSValue> create(JSSmart<CJSValue> Native, JSSmart<CJSValue> width_px, JSSmart<CJSValue> height_px, JSSmart<CJSValue> width_mm, JSSmart<CJSValue> height_mm);
JSSmart<CJSValue> Destroy();

View File

@ -2,7 +2,6 @@
#include "./../docbuilder_p.h"
#include "../../common/Directory.h"
#include "../server.h"
JSSmart<CJSValue> CBuilderDocumentEmbed::IsValid()
{
@ -69,23 +68,13 @@ void CBuilderDocumentEmbed::_OpenFile(const std::wstring& sFile, const std::wstr
int nConvertResult = pBuilder->ConvertToInternalFormat(m_sFolder, sFileCopy, sParams);
if (0 == nConvertResult)
{
if (CServerInstance::getInstance().IsEnable())
CServerInstance::getInstance().AddTmpFile(m_sFolder);
m_bIsValid = true;
}
}
void CBuilderDocumentEmbed::_CloseFile()
{
if (!m_sFolder.empty())
{
NSDirectory::DeleteDirectory(m_sFolder);
if (m_bIsValid && CServerInstance::getInstance().IsEnable())
CServerInstance::getInstance().RemoveTmpFile(m_sFolder);
}
m_bIsValid = false;
m_sFolder = L"";
}

View File

@ -10,35 +10,18 @@
#define M_PI 3.14159265358979323846
#endif
#ifdef _DEBUG
//#define ENABLE_GR_LOGS
#endif
namespace NSGraphics
{
void CGraphics::init(double width_px, double height_px, double width_mm, double height_mm)
void CGraphics::init(NSNativeControl::CNativeControl* oNative, double width_px, double height_px, double width_mm, double height_mm)
{
if (!m_pAppImage)
return;
if (NULL == m_pAppImage->GetFonts())
{
NSFonts::IApplicationFonts* pFonts = NSFonts::NSApplication::Create();
std::wstring sFontsDir = m_pAppImage->GetFontsDirectory();
pFonts->InitializeFromFolder(sFontsDir.empty() ? NSFile::GetProcessDirectory() : sFontsDir);
m_pAppImage->SetFonts(pFonts);
RELEASEINTERFACE(pFonts);
}
NSFonts::IFontManager* pManager = m_pAppImage->GetFonts()->GenerateFontManager();
#ifdef ENABLE_GR_LOGS
std::wcout << L"init "<<
m_pAppImage->GetImagesDirectory() << L" " <<
m_pAppImage->GetFontsDirectory() << L" " <<
width_px << L" " << height_px << L" " <<
width_mm << L" " << height_mm << std::endl;
m_sApplicationImagesDirectory = oNative->m_strImagesDirectory;
m_sApplicationFontsDirectory = oNative->m_strFontsDirectory;
#ifdef _DEBUG
std::wcout << L"init "<< m_sApplicationImagesDirectory << L" " << m_sApplicationFontsDirectory << L" " << width_px << L" " << height_px << L" " << width_mm << L" " << height_mm << std::endl;
#endif
m_pApplicationFonts = NSFonts::NSApplication::Create();
m_pApplicationFonts->InitializeFromFolder(m_sApplicationFontsDirectory.empty() ? NSFile::GetProcessDirectory() : m_sApplicationFontsDirectory);
NSFonts::IFontManager* pManager = m_pApplicationFonts->GenerateFontManager();
m_pRenderer = NSGraphics::Create();
m_pRenderer->SetFontManager(pManager);
@ -59,19 +42,7 @@ namespace NSGraphics
if (nRasterH < 1) nRasterH = 0;
}
int nExistW = 0;
int nExistH = 0;
BYTE* pData = m_pAppImage->GetBits(nExistW, nExistH);
if (pData != NULL)
{
nRasterW = nExistW;
nRasterH = nExistH;
}
else
{
pData = m_pAppImage->AllocBits(nRasterW, nRasterH);
}
BYTE* pData = new BYTE[4 * nRasterW * nRasterH];
unsigned int back = 0xffffff;
unsigned int* pData32 = (unsigned int*)pData;
unsigned int* pData32End = pData32 + nRasterW * nRasterH;
@ -84,21 +55,21 @@ namespace NSGraphics
m_oFrame.put_Stride(4 * nRasterW);
m_pRenderer->CreateFromBgraFrame(&m_oFrame);
m_pRenderer->SetSwapRGB(m_pAppImage->GetRgba());
m_pRenderer->SetSwapRGB(false);
m_pRenderer->put_Width(width_mm);
m_pRenderer->put_Height(height_mm);
}
void CGraphics::put_GlobalAlpha(bool enable, double alpha)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "put_GlobalAlpha " << enable << " " << alpha << std::endl;
#endif
m_pRenderer->put_GlobalAlphaEnabled(enable, alpha);
}
void CGraphics::End_GlobalAlpha()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "End_GlobalAlpha " << std::endl;
#endif
bool bIsInteger = m_pRenderer->get_IntegerGrid();
@ -115,7 +86,7 @@ namespace NSGraphics
}
void CGraphics::p_color(int r, int g, int b, int a)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "p_color " << r << " " << g << " " << b << " " << a << std::endl;
#endif
m_pRenderer->put_PenColor(r | (g << 8) | (b << 16));
@ -123,14 +94,14 @@ namespace NSGraphics
}
void CGraphics::p_width(double w)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "p_width " << w << std::endl;
#endif
m_pRenderer->put_PenSize(w / 1000.0);
}
void CGraphics::p_dash(size_t length, double* dash)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "p_dash " << length << std::endl;
#endif
if(length > 0)
@ -148,7 +119,7 @@ namespace NSGraphics
}
void CGraphics::b_color1(int r, int g, int b, int a)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "b_color1 " << r << " " << g << " " << b << " " << a << std::endl;
#endif
m_pRenderer->put_BrushType(c_BrushTypeSolid);
@ -157,7 +128,7 @@ namespace NSGraphics
}
void CGraphics::b_color2(int r, int g, int b, int a)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "b_color2 " << r << " " << g << " " << b << " " << a << std::endl;
#endif
m_pRenderer->put_BrushColor2(r | (g << 8) | (b << 16));
@ -165,42 +136,42 @@ namespace NSGraphics
}
void CGraphics::transform(double sx, double shy, double shx, double sy, double tx, double ty)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "transform " << sx << " " << shy << " " << shx << " " << sy << " " << tx << " " << ty << std::endl;
#endif
m_pRenderer->SetTransform(sx, shy, shx, sy, tx, ty);
}
void CGraphics::CalculateFullTransform()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "CalculateFullTransform " << std::endl;
#endif
m_pRenderer->CalculateFullTransform();
}
void CGraphics::_s()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "_s " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
}
void CGraphics::_e()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "_e " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
}
void CGraphics::_z()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "_z " << std::endl;
#endif
m_pRenderer->PathCommandClose();
}
void CGraphics::_m(double x, double y)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "_m " << x << " " << y << std::endl;
#endif
if (!m_pRenderer->get_IntegerGrid())
@ -213,7 +184,7 @@ namespace NSGraphics
}
void CGraphics::_l(double x, double y)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "_l " << x << " " << y << std::endl;
#endif
if (!m_pRenderer->get_IntegerGrid())
@ -226,7 +197,7 @@ namespace NSGraphics
}
void CGraphics::_c (double x1, double y1, double x2, double y2, double x3, double y3)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "_c " << x1 << " " << y1 << " " << x2 << " " << y2 << " " << x3 << " " << y3 << std::endl;
#endif
if (!m_pRenderer->get_IntegerGrid())
@ -241,7 +212,7 @@ namespace NSGraphics
}
void CGraphics::_c2(double x1, double y1, double x2, double y2)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "_c2 " << x1 << " " << y1 << " " << x2 << " " << y2 << std::endl;
#endif
if (!m_pRenderer->get_IntegerGrid())
@ -255,28 +226,28 @@ namespace NSGraphics
}
void CGraphics::ds()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "ds " << std::endl;
#endif
m_pRenderer->Stroke();
}
void CGraphics::df()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "df " << std::endl;
#endif
m_pRenderer->Fill();
}
void CGraphics::save()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "save " << std::endl;
#endif
m_oFrame.SaveFile(m_pAppImage->GetImagesDirectory() + L"/img.png", _CXIMAGE_FORMAT_PNG);
m_oFrame.SaveFile(m_sApplicationImagesDirectory + L"/img.png", _CXIMAGE_FORMAT_PNG);
}
void CGraphics::restore()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "restore " << std::endl;
#endif
m_pRenderer->BeginCommand(c_nResetClipType);
@ -284,7 +255,7 @@ namespace NSGraphics
}
void CGraphics::clip()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "clip " << std::endl;
#endif
m_pRenderer->BeginCommand(c_nClipType);
@ -292,46 +263,43 @@ namespace NSGraphics
}
void CGraphics::reset()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "reset " << std::endl;
#endif
m_pRenderer->ResetTransform();
}
void CGraphics::FreeFont()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "FreeFont " << std::endl;
#endif
m_pRenderer->CloseFont();
}
void CGraphics::ClearLastFont()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "ClearLastFont " << std::endl;
#endif
m_pRenderer->ClearInstallFont();
}
void CGraphics::drawImage(const std::wstring& img, double x, double y, double w, double h, BYTE alpha)
{
std::wstring strImage = img;
if (!NSFile::CFileBinary::Exists(img))
strImage = (0 == img.find(L"theme") ? m_pAppImage->GetThemesDirectory() : m_pAppImage->GetImagesDirectory()) + L'/' + img;
#ifdef ENABLE_GR_LOGS
std::wstring strImage = (0 == img.find(L"theme") ? m_sApplicationThemesDirectory : m_sApplicationImagesDirectory) + L'/' + img;
#ifdef _DEBUG
std::wcout << L"drawImage " << strImage << L" " << x << " " << y << L" " << w << L" " << h << L" " << alpha << std::endl;
#endif
m_pRenderer->DrawImageFromFile(strImage, x, y, w, h, alpha);
}
std::wstring CGraphics::GetFont()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "GetFont " << std::endl;
#endif
return m_pRenderer->GetFontManager()->GetName();
}
void CGraphics::SetFont(const std::wstring& name, int face, double size, int style)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::wcout << L"SetFont " << name << L" " << face << L" " << size << L" " << style << std::endl;
#endif
double DpiX, DpiY;
@ -346,21 +314,21 @@ namespace NSGraphics
}
void CGraphics::FillText(double x, double y, int text)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::wcout << L"FillText " << (wchar_t)text << L" " << x << L" " << y << std::endl;
#endif
m_pRenderer->CommandDrawTextCHAR(text, x, y, 0, 0);
}
void CGraphics::t(double x, double y, const std::wstring& text)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::wcout << L"t " << text << L" " << x << L" " << y << std::endl;
#endif
m_pRenderer->CommandDrawText(text, x, y, 0, 0);
}
void CGraphics::tg(int text, double x, double y)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::wcout << L"tg " << text << L" " << x << L" " << y << std::endl;
#endif
m_pRenderer->put_FontStringGID(TRUE);
@ -369,21 +337,21 @@ namespace NSGraphics
}
void CGraphics::SetIntegerGrid(bool param)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "SetIntegerGrid " << param << std::endl;
#endif
m_pRenderer->put_IntegerGrid(param);
}
bool CGraphics::GetIntegerGrid()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "GetIntegerGrid " << std::endl;
#endif
return m_pRenderer->get_IntegerGrid();
}
void CGraphics::DrawStringASCII (const std::wstring& text, double x, double y)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::wcout << L"DrawStringASCII " << text << L" " << x << L" " << y << std::endl;
#endif
double DpiY;
@ -405,7 +373,7 @@ namespace NSGraphics
}
void CGraphics::DrawHeaderEdit(double yPos)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "DrawHeaderEdit " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
@ -448,7 +416,7 @@ namespace NSGraphics
}
void CGraphics::DrawFooterEdit(double yPos)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "DrawFooterEdit " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
@ -491,7 +459,7 @@ namespace NSGraphics
}
void CGraphics::DrawLockParagraph (double x, double y1, double y2)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "DrawLockParagraph " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
@ -563,7 +531,7 @@ namespace NSGraphics
}
void CGraphics::DrawLockObjectRect(double x, double y, double w, double h)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "DrawLockObjectRect " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
@ -589,7 +557,7 @@ namespace NSGraphics
}
void CGraphics::DrawEmptyTableLine(double x1, double y1, double x2, double y2)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "DrawEmptyTableLine " << std::endl;
#endif
m_pRenderer->PathCommandEnd();
@ -674,7 +642,7 @@ namespace NSGraphics
}
void CGraphics::DrawSpellingLine (double y0, double x0, double x1, double w)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "DrawSpellingLine " << std::endl;
#endif
Aggplus::CMatrix* pMatrix = m_pRenderer->GetTransformMatrix();
@ -1020,7 +988,7 @@ namespace NSGraphics
}
void CGraphics::SaveGrState()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "SaveGrState " << std::endl;
#endif
CGrStateState* pState = new CGrStateState();
@ -1036,7 +1004,7 @@ namespace NSGraphics
}
void CGraphics::RestoreGrState()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "RestoreGrState " << std::endl;
#endif
if (m_oGrState.States.empty())
@ -1100,14 +1068,14 @@ namespace NSGraphics
}
void CGraphics::StartClipPath()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "StartClipPath " << std::endl;
#endif
m_pRenderer->BeginCommand(c_nClipType);
}
void CGraphics::EndClipPath()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "EndClipPath " << std::endl;
#endif
m_pRenderer->EndCommand(c_nClipType);
@ -1165,7 +1133,7 @@ namespace NSGraphics
}
std::string CGraphics::toDataURL(std::wstring type)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::wcout << "toDataURL " << type << std::endl;
#endif
std::wstring sFormat = (type.length() > 6) ? type.substr(6) : type;
@ -1210,11 +1178,11 @@ namespace NSGraphics
{
if (src.find(L"data:") == 0)
{
std::wstring strImage = m_pAppImage->GetImagesDirectory() + L"/texture.png";
std::wstring strImage = m_sApplicationImagesDirectory + L"/texture.png";
bool bIsOnlyOfficeHatch = false;
if(src.find(L"onlyoffice_hatch") != std::wstring::npos)
bIsOnlyOfficeHatch = true;
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::wcout << L"put_brushTexture " << src << L" " << type << std::endl;
#endif
src.erase(0, src.find(L',') + 1);
@ -1253,10 +1221,7 @@ namespace NSGraphics
}
else
{
std::wstring strImage = src;
if (!NSFile::CFileBinary::Exists(src))
strImage = (0 == src.find(L"theme") ? m_pAppImage->GetThemesDirectory() : m_pAppImage->GetImagesDirectory()) + L'/' + src;
std::wstring strImage = (0 == src.find(L"theme") ? m_sApplicationThemesDirectory : m_sApplicationImagesDirectory) + L'/' + src;
std::wstring sName = strImage.substr(0, strImage.rfind(L'.') + 1);
std::wstring sExt = src.substr(src.rfind(L'.') + 1);
if (sExt == L"svg")
@ -1266,7 +1231,7 @@ namespace NSGraphics
else if (NSFile::CFileBinary::Exists(sName + L"emf") && src.find(L"display") == 0)
strImage = sName + L"emf";
MetaFile::IMetaFile* pMetafile = MetaFile::Create(m_pAppImage->GetFonts());
MetaFile::IMetaFile* pMetafile = MetaFile::Create(m_pApplicationFonts);
pMetafile->LoadFromFile(strImage.c_str());
double x = 0, y = 0, w = 0, h = 0;
@ -1279,7 +1244,7 @@ namespace NSGraphics
}
else
sName += sExt;
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::wcout << L"put_brushTexture " << sName << L" " << type << std::endl;
#endif
m_pRenderer->put_BrushType(c_BrushTypeTexture);
@ -1289,21 +1254,21 @@ namespace NSGraphics
}
void CGraphics::put_brushTextureMode(int mode)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "put_brushTextureMode " << mode << std::endl;
#endif
m_pRenderer->put_BrushTextureMode(mode);
}
void CGraphics::put_BrushTextureAlpha(int a)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "put_BrushTextureAlpha " << a << std::endl;
#endif
m_pRenderer->put_BrushTextureAlpha(a == 0 ? 255 : a);
}
void CGraphics::put_BrushGradient(LONG* pColors, double* pPositions, size_t nCount, double x0, double y0, double x1, double y1, double r0, double r1)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "put_BrushGradient " << nCount << " " << x0 << " " << y0 << " " << x1 << " " << y1 << " " << r0 << " " << r1 << std::endl;
for (size_t i = 0; i < nCount; i++)
std::cout << pPositions[i] << " " << pColors[i] << " ";
@ -1328,7 +1293,7 @@ namespace NSGraphics
}
double CGraphics::TransformPointX(double x, double y)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "TransformPointX " << std::endl;
#endif
m_pRenderer->GetFullTransform()->TransformPoint(x, y);
@ -1336,7 +1301,7 @@ namespace NSGraphics
}
double CGraphics::TransformPointY(double x, double y)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "TransformPointY " << std::endl;
#endif
m_pRenderer->GetFullTransform()->TransformPoint(x, y);
@ -1344,14 +1309,14 @@ namespace NSGraphics
}
void CGraphics::put_LineJoin(int nJoin)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "put_LineJoin " << std::endl;
#endif
m_pRenderer->put_PenLineJoin(nJoin);
}
int CGraphics::GetLineJoin()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "GetLineJoin " << std::endl;
#endif
BYTE nRes;
@ -1360,7 +1325,7 @@ namespace NSGraphics
}
void CGraphics::put_TextureBounds(double x, double y, double w, double h)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "put_TextureBounds " << x << " " << y << " " << w << " " << h << std::endl;
#endif
if(m_pRenderer->get_IntegerGrid())
@ -1376,7 +1341,7 @@ namespace NSGraphics
}
double CGraphics::GetlineWidth()
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "GetlineWidth " << std::endl;
#endif
double nRes;
@ -1385,7 +1350,7 @@ namespace NSGraphics
}
void CGraphics::DrawPath(int path)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "DrawPath " << path << std::endl;
#endif
if(path == 257)
@ -1398,7 +1363,7 @@ namespace NSGraphics
}
void CGraphics::CoordTransformOffset(double tx, double ty)
{
#ifdef ENABLE_GR_LOGS
#ifdef _DEBUG
std::cout << "CoordTransformOffset " << tx << " " << ty << std::endl;
#endif
m_pRenderer->SetCoordTransformOffset(tx, ty);

View File

@ -7,7 +7,6 @@
#include "../common/File.h"
#include "nativecontrol.h"
#include "../graphics/pro/Graphics.h"
#include "embed/GraphicsEmbed.h"
namespace NSGraphics
{
@ -115,32 +114,28 @@ namespace NSGraphics
class CGraphics
{
public:
CGraphicsAppImage* m_pAppImage;
CBgraFrame m_oFrame;
std::wstring m_sApplicationFontsDirectory;
std::wstring m_sApplicationImagesDirectory;
std::wstring m_sApplicationThemesDirectory;
private:
NSFonts ::IApplicationFonts* m_pApplicationFonts;
NSGraphics::IGraphicsRenderer* m_pRenderer;
CBgraFrame m_oFrame;
CGrState m_oGrState;
public:
CGraphics()
{
m_pAppImage = NULL;
}
CGraphics() {}
~CGraphics()
{
Destroy();
}
void init(double width_px, double height_px, double width_mm, double height_mm);
void init(NSNativeControl::CNativeControl* oNative, double width_px, double height_px, double width_mm, double height_mm);
void Destroy()
{
int w, h;
if (m_pAppImage && m_pAppImage->GetBits(w, h))
m_oFrame.put_Data(NULL);
RELEASEINTERFACE(m_pRenderer);
RELEASEOBJECT(m_pAppImage);
RELEASEINTERFACE(m_pApplicationFonts);
}
void EndDraw() {}
void put_GlobalAlpha(bool enable, double globalAlpha);

View File

@ -54,9 +54,9 @@ v8::Local<v8::String> CreateV8String(v8::Isolate* i, const std::string& str);
#ifdef __ANDROID__
//#ifdef _DEBUG
#ifdef _DEBUG
#define ANDROID_LOGS
//#endif
#endif
#ifdef ANDROID_LOGS
#include <android/log.h>
@ -488,11 +488,7 @@ namespace NSJSBase
virtual CJSEmbedObject* getNative()
{
if (0 == value->InternalFieldCount())
return NULL;
v8::Handle<v8::External> field = v8::Handle<v8::External>::Cast(value->GetInternalField(0));
if (field.IsEmpty())
return NULL;
return (CJSEmbedObject*)field->Value();
}
@ -995,76 +991,67 @@ inline void js_return(const v8::PropertyCallbackInfo<v8::Value>& info, JSSmart<N
#define PROPERTY_GET(NAME, NAME_EMBED) \
void NAME(v8::Local<v8::String> _name, const v8::PropertyCallbackInfo<v8::Value>& info) \
{ \
CURRENTWRAPPER* _this = dynamic_cast<CURRENTWRAPPER*>(unwrap_native(info.Holder())); \
if (!_this) return; \
CURRENTWRAPPER* _this = (CURRENTWRAPPER*)unwrap_native(info.Holder()); \
JSSmart<CJSValue> ret = _this->NAME_EMBED(); \
js_return(info, ret); \
}
#define FUNCTION_WRAPPER_V8_0(NAME, NAME_EMBED) \
void NAME(const v8::FunctionCallbackInfo<v8::Value>& args) \
{ \
CURRENTWRAPPER* _this = dynamic_cast<CURRENTWRAPPER*>(unwrap_native(args.Holder())); \
if (!_this) return; \
JSSmart<CJSValue> ret = _this->NAME_EMBED(); \
js_return(args, ret); \
#define FUNCTION_WRAPPER_V8_0(NAME, NAME_EMBED) \
void NAME(const v8::FunctionCallbackInfo<v8::Value>& args) \
{ \
CURRENTWRAPPER* _this = (CURRENTWRAPPER*)unwrap_native(args.Holder()); \
JSSmart<CJSValue> ret = _this->NAME_EMBED(); \
js_return(args, ret); \
}
#define FUNCTION_WRAPPER_V8(NAME, NAME_EMBED) FUNCTION_WRAPPER_V8_0(NAME, NAME_EMBED)
#define FUNCTION_WRAPPER_V8_1(NAME, NAME_EMBED) \
void NAME(const v8::FunctionCallbackInfo<v8::Value>& args) \
{ \
CURRENTWRAPPER* _this = dynamic_cast<CURRENTWRAPPER*>(unwrap_native(args.Holder())); \
if (!_this) return; \
JSSmart<CJSValue> ret = _this->NAME_EMBED(js_value(args[0])); \
js_return(args, ret); \
#define FUNCTION_WRAPPER_V8_1(NAME, NAME_EMBED) \
void NAME(const v8::FunctionCallbackInfo<v8::Value>& args) \
{ \
CURRENTWRAPPER* _this = (CURRENTWRAPPER*)unwrap_native(args.Holder()); \
JSSmart<CJSValue> ret = _this->NAME_EMBED(js_value(args[0])); \
js_return(args, ret); \
}
#define FUNCTION_WRAPPER_V8_2(NAME, NAME_EMBED) \
void NAME(const v8::FunctionCallbackInfo<v8::Value>& args) \
{ \
CURRENTWRAPPER* _this = dynamic_cast<CURRENTWRAPPER*>(unwrap_native(args.Holder())); \
if (!_this) return; \
JSSmart<CJSValue> ret = _this->NAME_EMBED(js_value(args[0]), js_value(args[1])); \
js_return(args, ret); \
#define FUNCTION_WRAPPER_V8_2(NAME, NAME_EMBED) \
void NAME(const v8::FunctionCallbackInfo<v8::Value>& args) \
{ \
CURRENTWRAPPER* _this = (CURRENTWRAPPER*)unwrap_native(args.Holder()); \
JSSmart<CJSValue> ret = _this->NAME_EMBED(js_value(args[0]), js_value(args[1])); \
js_return(args, ret); \
}
#define FUNCTION_WRAPPER_V8_3(NAME, NAME_EMBED) \
void NAME(const v8::FunctionCallbackInfo<v8::Value>& args) \
{ \
CURRENTWRAPPER* _this = dynamic_cast<CURRENTWRAPPER*>(unwrap_native(args.Holder())); \
if (!_this) return; \
CURRENTWRAPPER* _this = (CURRENTWRAPPER*)unwrap_native(args.Holder()); \
JSSmart<CJSValue> ret = _this->NAME_EMBED(js_value(args[0]), js_value(args[1]), js_value(args[2])); \
js_return(args, ret); \
}
#define FUNCTION_WRAPPER_V8_4(NAME, NAME_EMBED) \
void NAME(const v8::FunctionCallbackInfo<v8::Value>& args) \
{ \
CURRENTWRAPPER* _this = dynamic_cast<CURRENTWRAPPER*>(unwrap_native(args.Holder())); \
if (!_this) return; \
CURRENTWRAPPER* _this = (CURRENTWRAPPER*)unwrap_native(args.Holder()); \
JSSmart<CJSValue> ret = _this->NAME_EMBED(js_value(args[0]), js_value(args[1]), js_value(args[2]), js_value(args[3])); \
js_return(args, ret); \
}
#define FUNCTION_WRAPPER_V8_5(NAME, NAME_EMBED) \
void NAME(const v8::FunctionCallbackInfo<v8::Value>& args) \
{ \
CURRENTWRAPPER* _this = dynamic_cast<CURRENTWRAPPER*>(unwrap_native(args.Holder())); \
if (!_this) return; \
CURRENTWRAPPER* _this = (CURRENTWRAPPER*)unwrap_native(args.Holder()); \
JSSmart<CJSValue> ret = _this->NAME_EMBED(js_value(args[0]), js_value(args[1]), js_value(args[2]), js_value(args[3]), js_value(args[4])); \
js_return(args, ret); \
}
#define FUNCTION_WRAPPER_V8_6(NAME, NAME_EMBED) \
void NAME(const v8::FunctionCallbackInfo<v8::Value>& args) \
{ \
CURRENTWRAPPER* _this = dynamic_cast<CURRENTWRAPPER*>(unwrap_native(args.Holder())); \
if (!_this) return; \
CURRENTWRAPPER* _this = (CURRENTWRAPPER*)unwrap_native(args.Holder()); \
JSSmart<CJSValue> ret = _this->NAME_EMBED(js_value(args[0]), js_value(args[1]), js_value(args[2]), js_value(args[3]), js_value(args[4]), js_value(args[5])); \
js_return(args, ret); \
}
#define FUNCTION_WRAPPER_V8_7(NAME, NAME_EMBED) \
void NAME(const v8::FunctionCallbackInfo<v8::Value>& args) \
{ \
CURRENTWRAPPER* _this = dynamic_cast<CURRENTWRAPPER*>(unwrap_native(args.Holder())); \
if (!_this) return; \
CURRENTWRAPPER* _this = (CURRENTWRAPPER*)unwrap_native(args.Holder()); \
JSSmart<CJSValue> ret = _this->NAME_EMBED(js_value(args[0]), js_value(args[1]), js_value(args[2]), js_value(args[3]), js_value(args[4]), \
js_value(args[5]), js_value(args[6])); \
js_return(args, ret); \
@ -1072,8 +1059,7 @@ inline void js_return(const v8::PropertyCallbackInfo<v8::Value>& info, JSSmart<N
#define FUNCTION_WRAPPER_V8_8(NAME, NAME_EMBED) \
void NAME(const v8::FunctionCallbackInfo<v8::Value>& args) \
{ \
CURRENTWRAPPER* _this = dynamic_cast<CURRENTWRAPPER*>(unwrap_native(args.Holder())); \
if (!_this) return; \
CURRENTWRAPPER* _this = (CURRENTWRAPPER*)unwrap_native(args.Holder()); \
JSSmart<CJSValue> ret = _this->NAME_EMBED(js_value(args[0]), js_value(args[1]), js_value(args[2]), js_value(args[3]), js_value(args[4]), \
js_value(args[5]), js_value(args[6]), js_value(args[7])); \
js_return(args, ret); \
@ -1081,8 +1067,7 @@ inline void js_return(const v8::PropertyCallbackInfo<v8::Value>& info, JSSmart<N
#define FUNCTION_WRAPPER_V8_9(NAME, NAME_EMBED) \
void NAME(const v8::FunctionCallbackInfo<v8::Value>& args) \
{ \
CURRENTWRAPPER* _this = dynamic_cast<CURRENTWRAPPER*>(unwrap_native(args.Holder())); \
if (!_this) return; \
CURRENTWRAPPER* _this = (CURRENTWRAPPER*)unwrap_native(args.Holder()); \
JSSmart<CJSValue> ret = _this->NAME_EMBED(js_value(args[0]), js_value(args[1]), js_value(args[2]), js_value(args[3]), js_value(args[4]), \
js_value(args[5]), js_value(args[6]), js_value(args[7]), js_value(args[8])); \
js_return(args, ret); \
@ -1090,8 +1075,7 @@ inline void js_return(const v8::PropertyCallbackInfo<v8::Value>& info, JSSmart<N
#define FUNCTION_WRAPPER_V8_10(NAME, NAME_EMBED) \
void NAME(const v8::FunctionCallbackInfo<v8::Value>& args) \
{ \
CURRENTWRAPPER* _this = dynamic_cast<CURRENTWRAPPER*>(unwrap_native(args.Holder())); \
if (!_this) return; \
CURRENTWRAPPER* _this = (CURRENTWRAPPER*)unwrap_native(args.Holder()); \
JSSmart<CJSValue> ret = _this->NAME_EMBED(js_value(args[0]), js_value(args[1]), js_value(args[2]), js_value(args[3]), js_value(args[4]), js_value(args[5]), \
js_value(args[6]), js_value(args[7]), js_value(args[8]), js_value(args[9])); \
js_return(args, ret); \
@ -1099,8 +1083,7 @@ inline void js_return(const v8::PropertyCallbackInfo<v8::Value>& info, JSSmart<N
#define FUNCTION_WRAPPER_V8_13(NAME, NAME_EMBED) \
void NAME(const v8::FunctionCallbackInfo<v8::Value>& args) \
{ \
CURRENTWRAPPER* _this = dynamic_cast<CURRENTWRAPPER*>(unwrap_native(args.Holder())); \
if (!_this) return; \
CURRENTWRAPPER* _this = (CURRENTWRAPPER*)unwrap_native(args.Holder()); \
JSSmart<CJSValue> ret = _this->NAME_EMBED(js_value(args[0]), js_value(args[1]), js_value(args[2]), js_value(args[3]), js_value(args[4]), js_value(args[5]), \
js_value(args[6]), js_value(args[7]), js_value(args[8]), js_value(args[9]), js_value(args[10]), js_value(args[11]), \
js_value(args[12])); \

View File

@ -99,11 +99,6 @@ namespace NSJSON
return m_internal->m_type == CTypedValue::vtObject;
}
bool IValue::IsImage() const
{
return m_internal->m_type == CTypedValue::vtImage;
}
bool IValue::ToBool() const
{
if (m_internal->m_type != CTypedValue::vtPrimitive)
@ -355,11 +350,6 @@ namespace NSJSON
strRes += "}";
break;
}
case CTypedValue::vtImage:
{
// TODO: implement like typed array?
break;
}
}
return strRes;
@ -507,82 +497,6 @@ namespace NSJSON
return static_cast<CObject*>(m_internal->m_value.get())->getPropertyNames();
}
const BYTE* IValue::GetImageBits() const
{
if (m_internal->m_type != CTypedValue::vtImage)
{
#ifdef JSON_DEBUG
throw std::bad_cast();
#endif
return nullptr;
}
return static_cast<CImage*>(m_internal->m_value.get())->getBits();
}
BYTE* IValue::GetImageBits()
{
return const_cast<BYTE*>(static_cast<const CValue&>(*this).GetImageBits());
}
int IValue::GetImageWidth() const
{
if (m_internal->m_type != CTypedValue::vtImage)
{
#ifdef JSON_DEBUG
throw std::bad_cast();
#endif
return 0;
}
return static_cast<CImage*>(m_internal->m_value.get())->getWidth();
}
int IValue::GetImageHeight() const
{
if (m_internal->m_type != CTypedValue::vtImage)
{
#ifdef JSON_DEBUG
throw std::bad_cast();
#endif
return 0;
}
return static_cast<CImage*>(m_internal->m_value.get())->getHeight();
}
ImageFormat IValue::GetImageFormat() const
{
if (m_internal->m_type != CTypedValue::vtImage)
{
#ifdef JSON_DEBUG
throw std::bad_cast();
#endif
return ImageFormat::ifInvalid;
}
return static_cast<CImage*>(m_internal->m_value.get())->getFormat();
}
void IValue::ImageExternalize()
{
if (m_internal->m_type != CTypedValue::vtImage)
{
#ifdef JSON_DEBUG
throw std::bad_cast();
#endif
return;
}
static_cast<CImage*>(m_internal->m_value.get())->externalize();
}
void IValue::ImageAlloc(const int& width, const int& height, const ImageFormat& format)
{
if (m_internal->m_type != CTypedValue::vtImage)
{
#ifdef JSON_DEBUG
throw std::bad_cast();
#endif
return;
}
static_cast<CImage*>(m_internal->m_value.get())->alloc(width, height, format);
}
CValue::CValue() : IValue()
{
@ -676,35 +590,6 @@ namespace NSJSON
NSJSBase::NSAllocator::Free(data, size);
}
CValue CValue::CreateImage(BYTE* bits, int width, int height, ImageFormat format, bool isExternalize)
{
CValue ret;
if (width <= 0 || height <= 0)
return ret;
ret.m_internal->m_value = std::make_shared<CImage>(bits, width, height, format, isExternalize);
ret.m_internal->m_type = CTypedValue::vtImage;
return ret;
}
CValue CValue::CreateEmptyImage(ImageFormat format)
{
CValue ret;
ret.m_internal->m_value = std::make_shared<CImage>((BYTE*)NULL, 0, 0, format, false);
ret.m_internal->m_type = CTypedValue::vtImage;
return ret;
}
BYTE* CValue::AllocImageBits(int width, int height)
{
return new BYTE[4 * width * height];
}
void CValue::FreeImageBits(BYTE* bits)
{
delete[] bits;
}
CValue CValue::CreateObject()
{
CValue ret;

View File

@ -20,7 +20,7 @@
#endif
// uncomment to enable exceptions throwing
// #define JSON_DEBUG
//#define JSON_DEBUG
#ifdef JSON_DEBUG
#include <stdexcept>
@ -29,14 +29,6 @@
namespace NSJSON
{
typedef unsigned char BYTE;
enum class ImageFormat
{
ifRGBA,
ifBGRA,
ifARGB,
ifInvalid
};
class CValue;
class CValueRef;
@ -96,10 +88,6 @@ namespace NSJSON
* Returns true if the value is an object.
*/
bool IsObject() const;
/**
* Returns true if the value is an image.
*/
bool IsImage() const;
// FUNCTIONS FOR WORKING WITH PRIMITIVE VALUES
/**
@ -205,39 +193,6 @@ namespace NSJSON
*/
std::vector<std::string> GetPropertyNames() const;
// FUNCTIONS FOR WORKING WITH IMAGES
/**
* Gets bits of image.
* @return the pointer to memory, allocated for the image. If current value is not an image, returns nullptr.
*/
const BYTE* GetImageBits() const;
BYTE* GetImageBits();
/**
* Gets width of the image.
* @returns Returns the width of the image. If current value is not an image, returns 0.
*/
int GetImageWidth() const;
/**
* Gets height of the image.
* @returns Returns the height of the image. If current value is not an image, returns 0.
*/
int GetImageHeight() const;
/**
* Gets format of the image.
* @returns Returns the image format. If current value is not an image, returns ImageFormat::ifInvalid.
*/
ImageFormat GetImageFormat() const;
/**
* Make image bits external.
*/
void ImageExternalize();
/**
* Alloc image bits as internal.
*/
void ImageAlloc(const int& width, const int& height, const ImageFormat& format);
protected:
std::shared_ptr<CTypedValue> m_internal;
};
@ -296,30 +251,6 @@ namespace NSJSON
*/
static void FreeTypedArray(BYTE* data, size_t size);
// IMAGE
/**
* Creates and returns new image object.
* @param bits The pointer to image data. The pointer should be acquired with AllocImageBits().
* @param width The width of the image.
* @param height The height of the image.
* @param format The format of the image.
* @param isExternalize If true the memory will not be reclaimed when the created image is destroyed.
* If this parameter is false then the memory will be released using FreeImageBits() during the image object destruction.
*/
static CValue CreateImage(BYTE* bits, int width, int height, ImageFormat format = ImageFormat::ifBGRA, bool isExternalize = true);
static CValue CreateEmptyImage(ImageFormat format = ImageFormat::ifBGRA);
/**
* Allocates the memory for an image.
* @param width The width of the image.
* @param height The height of the image.
*/
static BYTE* AllocImageBits(int width, int height);
/**
* Frees the memory for a image bits.
* @param data The allocated memory to be released.
*/
static void FreeImageBits(BYTE* bits);
// OBJECT CONSTRUCTOR
/**
* Creates and returns empty object.

View File

@ -17,8 +17,7 @@ namespace NSJSON
vtPrimitive,
vtArray,
vtTypedArray,
vtObject,
vtImage
vtObject
};
public:

View File

@ -211,56 +211,4 @@ namespace NSJSON
}
return ret;
}
CImage::CImage(BYTE* bits, const int& width, const int& height, const ImageFormat& format, const bool& isExternalize) :
m_bits(bits), m_width(width), m_height(height), m_format(format), m_isExternalize(isExternalize)
{
}
CImage::~CImage()
{
if (!m_isExternalize)
{
CValue::FreeImageBits(m_bits);
}
}
void CImage::alloc(const int& width, const int& height, const ImageFormat& format)
{
if (!m_isExternalize && m_bits)
{
CValue::FreeImageBits(m_bits);
}
m_bits = CValue::AllocImageBits(width, height);
m_width = width;
m_height = height;
m_format = format;
m_isExternalize = false;
}
BYTE* CImage::getBits()
{
return m_bits;
}
int CImage::getWidth()
{
return m_width;
}
int CImage::getHeight()
{
return m_height;
}
ImageFormat CImage::getFormat()
{
return m_format;
}
void CImage::externalize()
{
m_isExternalize = true;
}
}

View File

@ -113,28 +113,6 @@ namespace NSJSON
private:
storage_t m_values;
};
class CImage : public IBaseValue
{
public:
CImage(BYTE* bits, const int& width, const int& height, const ImageFormat& format, const bool& isExternalize = true);
~CImage();
public:
BYTE* getBits();
int getWidth();
int getHeight();
ImageFormat getFormat();
void externalize();
void alloc(const int& width, const int& height, const ImageFormat& format);
private:
BYTE* m_bits;
int m_width;
int m_height;
ImageFormat m_format;
bool m_isExternalize;
};
} // namespace
}
#endif // JSON_VALUES_H_

View File

@ -3,75 +3,9 @@
#include "json.h"
#include "../js_internal/js_base.h"
#include "../embed/GraphicsEmbed.h"
#include <cmath>
class CAppImageTo : public CGraphicsAppImage
{
private:
NSJSON::CValueRef* m_image;
public:
CAppImageTo(const NSJSON::CValue& image) : CGraphicsAppImage()
{
m_image = new NSJSON::CValueRef(image);
}
virtual ~CAppImageTo()
{
if (m_image)
delete m_image;
}
public:
virtual unsigned char* GetBits(int& w, int& h)
{
unsigned char* bits = m_image->GetImageBits();
if (NULL != bits)
{
w = m_image->GetImageWidth();
h = m_image->GetImageHeight();
}
return bits;
}
virtual unsigned char* AllocBits(const int& w, const int& h)
{
m_image->ImageAlloc(w, h, GetRgba() ? NSJSON::ImageFormat::ifRGBA : NSJSON::ImageFormat::ifBGRA);
return m_image->GetImageBits();
}
};
class CAppImageFrom : public CGraphicsAppImage
{
public:
unsigned char* m_pData;
int m_nW;
int m_nH;
public:
CAppImageFrom() : CGraphicsAppImage()
{
m_pData = NULL;
m_nW = 0;
m_nH = 0;
}
virtual ~CAppImageFrom()
{
}
public:
virtual unsigned char* GetBits(int& w, int& h)
{
return m_pData;
}
virtual unsigned char* AllocBits(const int& w, const int& h)
{
m_nW = w;
m_nH = h;
m_pData = NSJSON::CValue::AllocImageBits(w, h);
return m_pData;
}
};
namespace NSJSON
{
static JSSmart<NSJSBase::CJSValue> toJS(const CValue& value)
@ -116,12 +50,6 @@ namespace NSJSON
JSSmart<NSJSBase::CJSTypedArray> jsTypedArr = NSJSBase::CJSContext::createUint8Array(const_cast<BYTE*>(value.GetData()), value.GetCount());
ret = jsTypedArr->toValue();
}
else if (value.IsImage())
{
JSSmart<CJSObject> wrap = CJSContext::createEmbedObject("CGraphicsEmbed");
((CGraphicsEmbed*)wrap->getNative())->SetAppImage(new CAppImageTo(value));
ret = wrap->toValue();
}
// objects (there is no need for IsObject())
else
{
@ -202,25 +130,6 @@ namespace NSJSON
else if (jsValue->isObject())
{
JSSmart<NSJSBase::CJSObject> jsObj = jsValue->toObject();
CJSEmbedObject* pNative = jsObj->getNative();
if (pNative != NULL)
{
CGraphicsEmbed* pGrEmbed = dynamic_cast<CGraphicsEmbed*>(pNative);
if (pGrEmbed)
{
CAppImageFrom* pAppImage = dynamic_cast<CAppImageFrom*>(pGrEmbed->GetAppImage());
if (pAppImage)
{
return NSJSON::CValue::CreateImage(pAppImage->m_pData,
pAppImage->m_nW,
pAppImage->m_nH,
pAppImage->GetRgba() ? ImageFormat::ifRGBA : ImageFormat::ifBGRA,
false);
}
}
}
std::vector<std::string> properties = jsObj->getPropertyNames();
ret = CValue::CreateObject();
for (const std::string& name : properties)

View File

@ -44,10 +44,7 @@ CImagesWorker::CImagesWorker(const std::wstring& sFolder)
std::wstring CImagesWorker::GetImageLocal(const std::wstring& sUrl)
{
if (CServerInstance::getInstance().IsEnable())
{
if (!CServerInstance::getInstance().CheckTmpDirectory(sUrl))
return L"error";
}
return L"error";
std::wstring sExt = NSFile::GetFileExtention(sUrl);
std::wstring sRet = L"image" + std::to_wstring(m_nIndex++) + L"." + sExt;
m_mapImages.insert(std::make_pair(sUrl, sRet));

View File

@ -0,0 +1,9 @@
!*.vcxproj.user
!Makefile
out/
*.docx
*.pptx
*.xlsx
*.class

View File

@ -0,0 +1,156 @@
- [Document Builder samples](#document-builder-samples)
- [About](#about)
- [Project generator: configure.py](#project-generator-configurepy)
- [Running C++ samples](#running-c-samples)
- [Visual Studio](#visual-studio)
- [Qt](#qt)
- [Makefile](#makefile)
- [Running C# samples](#running-c-samples-1)
- [Visual Studio](#visual-studio-1)
- [Running Python samples](#running-python-samples)
- [Running Java samples](#running-java-samples)
# Document Builder samples
## About
Here you can find some code samples for Document Builder library in different programming languages:
1. [C++](#running-c-samples)
2. [C# (.NET)](#running-c-samples-1)
3. [Python](#running-python-samples)
4. [Java](#running-java-samples)
## Project generator: configure.py
For running C++ and C# code samples use python script `configure/configure.py` which is able to generate:
+ Visual Studio project files
+ Qt project file
+ Makefile
To use `configure.py` you need to specify following options:
1. Which project files to generate: `--vs`, `--qt` or `--make`. Several options are available at the same time, but some of them are not supported on all platforms. In case you provide none of these options, all available projects will be generated.
2. Test samples with `--test TEST`. Some available options:
- `--test all` generate projects for both C++ and C#.
- `--test cpp` generate projects only for C++ samples
- `--test cs` generate projects only for C# samples.
- `--test cpp/creating_basic_form` generate only project for the specified sample.
Several test options are available at the same time. To see all available `TEST` options call `configure.py -l`.
3. Directory to the Document Builder with `--dir DIR`. If Document Builder is not installed in default path you have to provide path to it.
Generated files will be located in the `out` directory inside of the corresponding test folders.
## Running C++ samples
If Document Builder is not installed in `C:/Program Files/ONLYOFFICE/DocumentBuilder`, for every C++ sample you should change the `workDir` variable at the beginning of *main.cpp* to actual location of Document Builder directory.
### Visual Studio
> **NOTE:** Only available on Windows
1. Use `configure.py` to generate VS project files. For example:
```shell
python configure.py --vs --test cpp/creating_basic_form --test cpp/creating_advanced_form
```
2. Open `.sln` file in Visual Studio. It will prompt you to retarget Windows SDK and VS toolset to your installed version click "OK".
3. The solution is ready to be built and run. Documents will be created in the project files directory.
### Qt
1. Use `configure.py` to generate Qt project files. For example:
```shell
python configure.py --qt --test cpp
```
2. Open `.pro` file in Qt Creator.
3. The project is ready to be built and run. Documents will be created in the `build` directory.
### Makefile
> **NOTE:** Only available on Linux and Mac OS.
1. Use `configure.py` to generate Makefile. For example:
```shell
python configure.py --make --test cpp/filling_spreadsheet
```
2. Go to the directory with generated Makefile:
```shell
cd ../out/cpp/filling_spreadsheet
```
3. Call
```shell
make
```
`make` will build and run the executable. Documents will be created in the same directory as Makefile is.
## Running C# samples
> **NOTE:** Only available on Windows with Visual Studio and .NET SDK installed
If Document Builder is not installed in `C:/Program Files/ONLYOFFICE/DocumentBuilder`, for every C# sample you should change the `workDirectory` variable at the beginning of `Main` function to actual location of Document Builder directory.
### Visual Studio
1. Use `configure.py` to generate VS project files. For example:
```shell
python configure.py --vs --test cs
```
2. Open `.sln` file in Visual Studio. Depending on your installed .NET SDK version you may need to set different target framework by setting it in Visual Studio project properties or editing it directly in the `.csproj` file.
3. The solution is ready to be built and run. Documents will be created in the project files directory.
## Running Python samples
1. Go to test directory:
```shell
cd python/creating_basic_form
```
2. If it is needed, edit path to builder directory at the beginning of the python script:
```py
sys.path.append('C:/Program Files/ONLYOFFICE/DocumentBuilder')
```
3. Run the script
```shell
python main.py
```
Documents will be created in the test directory.
## Running Java samples
> **NOTE:** JDK 8 or newer is required
1. Go to test directory:
```shell
cd java/creating_presentation
```
2. Compile the `Program.java` providing the path to ***docbuilder.jar***, located in the Document Builder directory:
```shell
javac -cp "C:\Program Files\ONLYOFFICE\DocumentBuilder\docbuilder.jar" Program.java
```
3. `.class` file should appear in the directory. Run the program:
```shell
java -cp "C:\Program Files\ONLYOFFICE\DocumentBuilder\docbuilder.jar;." Program
```
Note, that on UNIX systems the path separator is `:` instead of `;`. Thus, on Linux or Mac OS it should be:
```shell
java -cp "/opt/onlyoffice/documentbuilder/docbuilder.jar:." Program
```
3. Documents will be created in the test directory.

View File

@ -0,0 +1,293 @@
import os
import argparse
import platform
import uuid
langs = ['cpp', 'cs']
os_name = platform.system().lower()
def mkdir(dir):
if not os.path.exists(dir):
os.mkdir(dir)
def log(level, message):
print('configure.py: ' + level + ': ' + message)
def getDefaultBuilderDir():
dir = ''
if os_name == 'windows':
dir = 'C:\\Program Files\\ONLYOFFICE\\DocumentBuilder'
elif os_name == 'linux':
dir = '/opt/onlyoffice/documentbuilder'
return dir
def getAllTests():
tests = {}
for lang in langs:
tests[lang] = []
test_dirs = os.listdir(lang)
for test_dir in test_dirs:
if not os.path.isdir(lang + '/' + test_dir):
continue
tests[lang].append(lang + '/' + test_dir)
return tests
def printAvailableTests():
all_tests = getAllTests()
print('all')
for lang in langs:
print('-----')
print(lang)
tests = all_tests[lang]
for test in tests:
print(test)
class PrintTestsList(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
printAvailableTests()
exit()
def getSelectedTests(tests):
all_tests = getAllTests()
# make set of all available tests
tests_set = {'all'}
for lang in langs:
tests_set.add(lang)
tests_set.update(all_tests[lang])
# make dict with set of selected tests
tests_selected = {lang: set() for lang in langs}
# filter tests through only available ones
for test in tests:
if not test in tests_set:
log('warning', 'wrong test "' + test + '". Call script with --list (or -l) to see all available tests')
continue
if test == 'all':
for lang in langs:
tests_selected[lang].update(all_tests[lang])
elif not '/' in test:
lang = test
tests_selected[lang].update(all_tests[lang])
else:
lang = test.split('/')[0]
tests_selected[lang].add(test)
# delete empty tests
for lang in langs:
if not tests_selected[lang]:
del tests_selected[lang]
return tests_selected
def replacePlaceholders(template_file, output_file, replacements):
content = ''
# open and read template file
with open(template_file, 'r') as file:
content = file.read()
# replace all placeholders with corresponding values
for placeholder, replacement in replacements.items():
content = content.replace(placeholder, replacement)
# write result to output file
with open(output_file, 'w') as file:
file.write(content)
def genVSProjectsCPP(tests, builder_dir):
for test in tests:
test_dir = 'out/' + test
mkdir(test_dir)
test_name = test.split('/')[1]
if os.path.exists(test_dir + '/' + test_name + '.vcxproj'):
log('info', 'VS C++ project for sample "' + test + '" already exists. Skipping.')
continue
else:
log('info', 'generating VS C++ project for sample "' + test + '"...')
# .vcxproj
project_guid = str(uuid.uuid4())
replacements = {
'[PROJECT_GUID]': project_guid,
'[TEST_NAME]': test_name,
'[BUILDER_DIR]': builder_dir,
'[ROOT_DIR]': os.getcwd()
}
replacePlaceholders('configure/project_templates/cpp/template.vcxproj', test_dir + '/' + test_name + '.vcxproj', replacements)
# .sln
replacements = {
'[SOLUTION_GUID]': str(uuid.uuid4()).upper(),
'[TEST_NAME]': test_name,
'[PROJECT_GUID]': project_guid.upper(),
'[EXT_GLOBALS_GUID]': str(uuid.uuid4()).upper()
}
replacePlaceholders('configure/project_templates/cpp/template.sln', test_dir + '/' + test_name + '.sln', replacements)
# .vcxproj.filters
replacements = {
'[GUID_SOURCE_FILES]': str(uuid.uuid4()).upper(),
'[GUID_HEADER_FILES]': str(uuid.uuid4()).upper(),
'[GUID_RESOURCE_FILES]': str(uuid.uuid4()).upper(),
'[TEST_NAME]': test_name
}
replacePlaceholders('configure/project_templates/cpp/template.vcxproj.filters', test_dir + '/' + test_name + '.vcxproj.filters', replacements)
# .vcxproj.user
replacements = {
'[BUILDER_DIR]': builder_dir
}
replacePlaceholders('configure/project_templates/cpp/template.vcxproj.user', test_dir + '/' + test_name + '.vcxproj.user', replacements)
def genVSProjectsCS(tests, builder_dir):
for test in tests:
test_dir = 'out/' + test
mkdir(test_dir)
test_name = test.split('/')[1]
if os.path.exists(test_dir + '/' + test_name + '.csproj'):
log('info', 'VS C# project for sample "' + test + '" already exists. Skipping.')
continue
else:
log('info', 'generating VS C# project for sample "' + test + '"...')
# .csproj
project_guid = str(uuid.uuid4())
replacements = {
'[TEST_NAME]': test_name,
'[BUILDER_DIR]': builder_dir,
}
replacePlaceholders('configure/project_templates/cs/template.csproj', test_dir + '/' + test_name + '.csproj', replacements)
# .sln
replacements = {
'[SOLUTION_GUID]': str(uuid.uuid4()).upper(),
'[TEST_NAME]': test_name,
'[PROJECT_GUID]': project_guid.upper(),
'[EXT_GLOBALS_GUID]': str(uuid.uuid4()).upper()
}
replacePlaceholders('configure/project_templates/cs/template.sln', test_dir + '/' + test_name + '.sln', replacements)
def genVSProjects(tests_selected, builder_dir):
if os_name != 'windows':
log('warning', 'generating Visual Studio projects is only available on Windows')
return
builder_dir = builder_dir.replace('/', '\\')
for lang, tests in tests_selected.items():
mkdir('out/' + lang)
if lang == 'cpp':
genVSProjectsCPP(tests, builder_dir)
elif lang == 'cs':
genVSProjectsCS(tests, builder_dir)
def genQtProjects(tests_selected, builder_dir):
# only for C++ projects
if 'cpp' not in tests_selected:
return
root_dir = os.getcwd()
if os_name == 'windows':
builder_dir = builder_dir.replace('\\', '/')
root_dir = root_dir.replace('\\', '/')
tests = tests_selected['cpp']
mkdir('out/cpp')
for test in tests:
test_dir = 'out/' + test
mkdir(test_dir)
test_name = test.split('/')[1]
if os.path.exists(test_dir + '/' + test_name + '.pro'):
log('info', 'Qt project for sample "' + test + '" already exists. Skipping.')
continue
else:
log('info', 'generating Qt C++ project for sample "' + test + '"...')
# .pro
replacements = {
'[TEST_NAME]': test_name,
'[BUILDER_DIR]': builder_dir,
'[ROOT_DIR]': root_dir
}
replacePlaceholders('configure/project_templates/cpp/template.pro', test_dir + '/' + test_name + '.pro', replacements)
def genMakefile(tests_selected, builder_dir):
# only for C++ projects
if 'cpp' not in tests_selected:
return
if os_name == 'windows':
log('warning', 'generating Makefile is not available on Windows')
return
# initialize variables
compiler = ''
lflags = ''
env_lib_path = ''
if os_name == 'linux':
compiler = 'g++'
lflags = '-Wl,--unresolved-symbols=ignore-in-shared-libs'
env_lib_path = 'LD_LIBRARY_PATH'
elif os_name == 'darwin':
compiler = 'clang++'
env_lib_path = 'DYLD_LIBRARY_PATH'
root_dir = os.getcwd()
tests = tests_selected['cpp']
mkdir('out/cpp')
for test in tests:
test_dir = 'out/' + test
mkdir(test_dir)
test_name = test.split('/')[1]
if os.path.exists(test_dir + '/Makefile'):
log('info', 'Makefile for sample "' + test + '" already exists. Skipping.')
else:
log('info', 'generating Makefile for C++ sample "' + test + '"...')
continue
# Makefile
replacements = {
'[TEST_NAME]': test_name,
'[BUILDER_DIR]': builder_dir,
'[ROOT_DIR]': root_dir,
'[COMPILER]': compiler,
'[LFLAGS]': lflags,
'[ENV_LIB_PATH]': env_lib_path
}
replacePlaceholders('configure/project_templates/cpp/Makefile', test_dir + '/Makefile', replacements)
if __name__ == '__main__':
# go to root dir
file_dir = os.path.dirname(os.path.realpath(__file__))
os.chdir(file_dir + '/..')
# initialize argument parser
parser = argparse.ArgumentParser(description='Generate project files for Document Builder samples')
parser.add_argument('--vs', action='store_true', help='create Visual Studio (.vcxproj and .csproj) project files')
parser.add_argument('--qt', action='store_true', help='create Qt (.pro) project files')
parser.add_argument('--make', action='store_true', help='create Makefile')
parser.add_argument('-t', '--test', dest='tests', action='append', help='specifies tests to generate project files', required=True)
parser.add_argument('-l', '--list', action=PrintTestsList, nargs=0, help='show list of available tests and exit')
builder_dir = getDefaultBuilderDir()
if builder_dir:
parser.add_argument('--dir', action='store', help='specifies Document Builder directory (default: ' + builder_dir + ')', default=builder_dir)
else:
parser.add_argument('--dir', action='store', help='specifies Document Builder directory', required=True)
args = parser.parse_args()
# validate arguments
if not os.path.exists(args.dir):
log('error', 'Document Builder directory doesn\'t exist: ' + args.dir)
exit(1)
if not (args.vs or args.qt or args.make):
if os_name == 'windows':
args.vs = True
args.qt = True
if os_name != 'windows':
args.make = True
# filter tests
tests_selected = getSelectedTests(args.tests)
# generate projects
mkdir('out')
# VS
if args.vs:
genVSProjects(tests_selected, args.dir)
elif 'cs' in tests_selected:
log('warning', 'generating C# projects only available ' + ('on Windows ' if os_name != 'windows' else '') + 'with --vs')
# Qt
if args.qt:
genQtProjects(tests_selected, args.dir)
# Makefile
if args.make:
genMakefile(tests_selected, args.dir)

View File

@ -0,0 +1,29 @@
CXX = [COMPILER]
CXXFLAGS = -std=gnu++11 -Wall -W -fPIC
INCPATH = -I[BUILDER_DIR]/include -I[ROOT_DIR]
LINK = [COMPILER]
LFLAGS = [LFLAGS]
LIBS = -L[BUILDER_DIR] -ldoctrenderer
BUILD_DIR = build
SRC = ../../../cpp/[TEST_NAME]/main.cpp
OBJ = $(BUILD_DIR)/main.o
TARGET = $(BUILD_DIR)/[TEST_NAME]
.PHONY: all run clean
all: $(TARGET) run
$(TARGET): $(OBJ)
$(LINK) $(LFLAGS) -o $(TARGET) $(OBJ) $(LIBS)
$(OBJ): $(SRC)
@test -d $(BUILD_DIR) || mkdir -p $(BUILD_DIR)
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o $(OBJ) $(SRC)
run: $(TARGET)
[ENV_LIB_PATH]="[BUILDER_DIR]" ./$(TARGET)
clean:
@rm -rf $(BUILD_DIR)

View File

@ -0,0 +1,17 @@
TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
TARGET = [TEST_NAME]
DESTDIR = $$PWD/build
BUILDER_DIR = "[BUILDER_DIR]"
ROOT_DIR = "[ROOT_DIR]"
INCLUDEPATH += $$BUILDER_DIR/include
INCLUDEPATH += $$ROOT_DIR
LIBS += -L$$BUILDER_DIR -ldoctrenderer
linux: QMAKE_LFLAGS += -Wl,--unresolved-symbols=ignore-in-shared-libs
SOURCES += ../../../cpp/[TEST_NAME]/main.cpp

View File

@ -0,0 +1,29 @@

Microsoft Visual Studio Solution File, Format Version 12.00
MinimumVisualStudioVersion = 10.0.40219.1
Project("{[SOLUTION_GUID]}") = "[TEST_NAME]", "[TEST_NAME].vcxproj", "{[PROJECT_GUID]}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{[PROJECT_GUID]}.Debug|x64.ActiveCfg = Debug|x64
{[PROJECT_GUID]}.Debug|x64.Build.0 = Debug|x64
{[PROJECT_GUID]}.Debug|x86.ActiveCfg = Debug|Win32
{[PROJECT_GUID]}.Debug|x86.Build.0 = Debug|Win32
{[PROJECT_GUID]}.Release|x64.ActiveCfg = Release|x64
{[PROJECT_GUID]}.Release|x64.Build.0 = Release|x64
{[PROJECT_GUID]}.Release|x86.ActiveCfg = Release|Win32
{[PROJECT_GUID]}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {[EXT_GLOBALS_GUID]}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,147 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{[PROJECT_GUID]}</ProjectGuid>
<RootNamespace>[TEST_NAME]</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<IncludePath>[BUILDER_DIR]\include;[ROOT_DIR];$(IncludePath)</IncludePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<IncludePath>[BUILDER_DIR]\include;[ROOT_DIR];$(IncludePath)</IncludePath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>[BUILDER_DIR];%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>doctrenderer.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>[BUILDER_DIR];%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>doctrenderer.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\..\..\cpp\[TEST_NAME]\main.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{[GUID_SOURCE_FILES]}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{[GUID_HEADER_FILES]}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{[GUID_RESOURCE_FILES]}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\..\cpp\[TEST_NAME]\main.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LocalDebuggerEnvironment>PATH=[BUILDER_DIR];%PATH%
$(LocalDebuggerEnvironment)</LocalDebuggerEnvironment>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LocalDebuggerEnvironment>PATH=[BUILDER_DIR];%PATH%
$(LocalDebuggerEnvironment)</LocalDebuggerEnvironment>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\cs\[TEST_NAME]\Program.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="[BUILDER_DIR]\docbuilder.net.dll" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,23 @@

Microsoft Visual Studio Solution File, Format Version 12.00
MinimumVisualStudioVersion = 10.0.40219.1
Project("{[SOLUTION_GUID]}") = "[TEST_NAME]", "[TEST_NAME].csproj", "{[PROJECT_GUID]}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{[PROJECT_GUID]}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{[PROJECT_GUID]}.Debug|Any CPU.Build.0 = Debug|Any CPU
{[PROJECT_GUID]}.Release|Any CPU.ActiveCfg = Release|Any CPU
{[PROJECT_GUID]}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {[EXT_GLOBALS_GUID]}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,90 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include <string>
#include "common.h"
#include "docbuilder.h"
#include "resources/utils/utils.h"
using namespace std;
using namespace NSDoctRenderer;
const wchar_t* workDir = L"C:\\Program Files\\ONLYOFFICE\\DocumentBuilder";
const wchar_t* resultPath = L"result.xlsx";
// Helper functions
void CheckCell(CValue oWorksheet, wstring cell, int row, int col)
{
if (cell.find('#') != std::wstring::npos)
{
wstring commentMsg = L"Error: " + cell;
CValue errorCell = oWorksheet.Call("GetRangeByNumber", row, col);
errorCell.Call("AddComment", commentMsg.c_str());
}
}
// Main function
int main()
{
// Init DocBuilder
CDocBuilder::Initialize(workDir);
CDocBuilder oBuilder;
oBuilder.SetProperty("--work-directory", workDir);
// Open file and get context
wstring templatePath = NSUtils::GetResourcesDirectory() + L"/docs/spreadsheet_with_errors.xlsx";
oBuilder.OpenFile(templatePath.c_str(), L"");
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Find and comment formula errors
CValue oWorksheet = oApi.Call("GetActiveSheet");
CValue oRange = oWorksheet.Call("GetUsedRange");
CValue data = oRange.Call("GetValue");
for (int row = 0; row < (int)data.GetLength(); row++)
{
for (int col = 0; col < (int)data[0].GetLength(); col++)
{
CheckCell(oWorksheet, data[row][col].ToString().c_str(), row, col);
}
}
// Save and close
oBuilder.SaveFile(OFFICESTUDIO_FILE_SPREADSHEET_XLSX, resultPath);
oBuilder.CloseFile();
CDocBuilder::Dispose();
return 0;
}

View File

@ -0,0 +1,206 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include <string>
#include "common.h"
#include "docbuilder.h"
using namespace std;
using namespace NSDoctRenderer;
const wchar_t* workDir = L"C:\\Program Files\\ONLYOFFICE\\DocumentBuilder";
const wchar_t* resultPath = L"result.docx";
// Helper functions
string cValueToString(CValue value)
{
wchar_t* txt = value.ToString().c_str();
wstring ws(txt);
string str(ws.begin(), ws.end());
return str;
}
void setTableBorders(CValue oTable, int borderColor)
{
oTable.Call("SetTableBorderTop", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderBottom", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderLeft", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderRight", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderInsideV", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderInsideH", "single", 4, 0, borderColor, borderColor, borderColor);
}
CValue createFullWidthTable(CValue oApi, int rows, int cols, int borderColor)
{
CValue oTable = oApi.Call("CreateTable", cols, rows);
oTable.Call("SetWidth", "percent", 100);
setTableBorders(oTable, borderColor);
return oTable;
}
CValue getTableCellParagraph(CValue oTable, int row, int col)
{
return oTable.Call("GetCell", row, col).Call("GetContent").Call("GetElement", 0);
}
void addTextToParagraph(CValue oParagraph, std::string text, int fontSize, bool isBold)
{
oParagraph.Call("AddText", text.c_str());
oParagraph.Call("SetFontSize", fontSize);
oParagraph.Call("SetBold", isBold);
}
void setPictureFormProperties(CValue oPictureForm, std::string key, std::string tip, bool required, std::string placeholder, std::string scaleFlag, bool lockAspectRatio, bool respectBorders, int shiftX, int shiftY, std::string imageUrl)
{
oPictureForm.Call("SetFormKey", key.c_str());
oPictureForm.Call("SetTipText", tip.c_str());
oPictureForm.Call("SetRequired", required);
oPictureForm.Call("SetPlaceholderText", placeholder.c_str());
oPictureForm.Call("SetScaleFlag", scaleFlag.c_str());
oPictureForm.Call("SetLockAspectRatio", lockAspectRatio);
oPictureForm.Call("SetRespectBorders", respectBorders);
oPictureForm.Call("SetPicturePosition", shiftX, shiftY);
oPictureForm.Call("SetImage", imageUrl.c_str());
}
void setTextFormProperties(CValue oTextForm, string key, string tip, bool required, string placeholder, bool comb, int maxCharacters, int cellWidth, bool multiLine, bool autoFit)
{
oTextForm.Call("SetFormKey", key.c_str());
oTextForm.Call("SetTipText", tip.c_str());
oTextForm.Call("SetRequired", required);
oTextForm.Call("SetPlaceholderText", placeholder.c_str());
oTextForm.Call("SetComb", comb);
oTextForm.Call("SetCharactersLimit", maxCharacters);
oTextForm.Call("SetCellWidth", cellWidth);
oTextForm.Call("SetCellWidth", multiLine);
oTextForm.Call("SetMultiline", autoFit);
}
void addTextFormToParagraph(CValue oParagraph, CValue oTextForm, int fontSize, string jc, bool hasBorder, int borderColor)
{
if (hasBorder)
{
oTextForm.Call("SetBorderColor", borderColor, borderColor, borderColor);
}
oParagraph.Call("AddElement", oTextForm);
oParagraph.Call("SetFontSize", fontSize);
oParagraph.Call("SetJc", jc.c_str());
}
// Main function
int main()
{
// Init DocBuilder
CDocBuilder::Initialize(workDir);
CDocBuilder oBuilder;
oBuilder.SetProperty("--work-directory", workDir);
oBuilder.CreateFile(OFFICESTUDIO_FILE_DOCUMENT_DOCX);
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Create advanced form
CValue oDocument = oApi.Call("GetDocument");
CValue oTable = createFullWidthTable(oApi, 1, 2, 255);
CValue oParagraph = getTableCellParagraph(oTable, 0, 0);
addTextToParagraph(oParagraph, "PURCHASE ORDER", 36, true);
oParagraph = getTableCellParagraph(oTable, 0, 1);
addTextToParagraph(oParagraph, "Serial # ", 25, true);
CValue oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "Serial", "Enter serial number", false, "Serial", true, 6, 1, false, false);
addTextFormToParagraph(oParagraph, oTextForm, 25, "left", true, 255);
oDocument.Call("Push", oTable);
CValue oPictureForm = oApi.Call("CreatePictureForm");
setPictureFormProperties(oPictureForm, "Photo", "Upload company logo", false, "Photo", "tooBig", false, false, 0, 0, "https://api.onlyoffice.com/content/img/docbuilder/examples/user-profile.png");
oParagraph = oApi.Call("CreateParagraph");
oParagraph.Call("AddElement", oPictureForm);
oDocument.Call("Push", oParagraph);
oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "Company Name", "Enter company name", false, "Company Name", true, 20, 1, false, false);
oParagraph = oApi.Call("CreateParagraph");
addTextFormToParagraph(oParagraph, oTextForm, 35, "left", false, 255);
oDocument.Call("Push", oParagraph);
oParagraph = oApi.Call("CreateParagraph");
addTextToParagraph(oParagraph, "Date: ", 25, true);
oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "Date", "Date", false, "DD.MM.YYYY", true, 10, 1, false, false);
addTextFormToParagraph(oParagraph, oTextForm, 25, "left", true, 255);
oDocument.Call("Push", oParagraph);
oParagraph = oApi.Call("CreateParagraph");
addTextToParagraph(oParagraph, "To:", 35, true);
oDocument.Call("Push", oParagraph);
oTable = createFullWidthTable(oApi, 1, 1, 200);
oParagraph = getTableCellParagraph(oTable, 0, 0);
oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "Recipient", "Recipient", false, "Recipient", true, 25, 1, false, false);
addTextFormToParagraph(oParagraph, oTextForm, 32, "left", false, 255);
oDocument.Call("Push", oTable);
oTable = createFullWidthTable(oApi, 10, 2, 200);
oTable.Call("GetRow", 0).Call("SetBackgroundColor", 245, 245, 245, false);
CValue oCell = oTable.Call("GetCell", 0, 0);
oCell.Call("SetWidth", "percent", 30);
oParagraph = getTableCellParagraph(oTable, 0, 0);
addTextToParagraph(oParagraph, "Qty.", 30, true);
oParagraph = getTableCellParagraph(oTable, 0, 1);
addTextToParagraph(oParagraph, "Description", 30, true);
for (int i = 1; i < 10; i++)
{
CValue oTempParagraph = getTableCellParagraph(oTable, i, 0);
CValue oTempTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTempTextForm, "Qty" + std::to_string(i), "Qty" + std::to_string(i), false, " ", true, 9, 1, false, false);
addTextFormToParagraph(oTempParagraph, oTempTextForm, 30, "left", false, 255);
oTempParagraph = getTableCellParagraph(oTable, i, 1);
oTempTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTempTextForm, "Description" + std::to_string(i), "Description" + std::to_string(i), false, " ", true, 22, 1, false, false);
addTextFormToParagraph(oTempParagraph, oTempTextForm, 30, "left", false, 255);
}
oDocument.Call("Push", oTable);
oDocument.Call("RemoveElement", 0);
oDocument.Call("RemoveElement", 1);
// Save and close
oBuilder.SaveFile(OFFICESTUDIO_FILE_DOCUMENT_DOCX, resultPath);
oBuilder.CloseFile();
CDocBuilder::Dispose();
return 0;
}

View File

@ -0,0 +1,108 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include <string>
#include "common.h"
#include "docbuilder.h"
using namespace NSDoctRenderer;
const wchar_t* workDir = L"C:\\Program Files\\ONLYOFFICE\\DocumentBuilder";
const wchar_t* resultPath = L"result.docx";
// Helper functions
void setPictureFormProperties(CValue oPictureForm, std::string key, std::string tip, bool required, std::string placeholder, std::string scaleFlag, bool lockAspectRatio, bool respectBorders, int shiftX, int shiftY, std::string imageUrl)
{
oPictureForm.Call("SetFormKey", key.c_str());
oPictureForm.Call("SetTipText", tip.c_str());
oPictureForm.Call("SetRequired", required);
oPictureForm.Call("SetPlaceholderText", placeholder.c_str());
oPictureForm.Call("SetScaleFlag", scaleFlag.c_str());
oPictureForm.Call("SetLockAspectRatio", lockAspectRatio);
oPictureForm.Call("SetRespectBorders", respectBorders);
oPictureForm.Call("SetPicturePosition", shiftX, shiftY);
oPictureForm.Call("SetImage", imageUrl.c_str());
}
void setTextFormProperties(CValue oTextForm, std::string key, std::string tip, bool required, std::string placeholder, bool comb, int maxCharacters, int cellWidth, bool multiLine, bool autoFit)
{
oTextForm.Call("SetFormKey", key.c_str());
oTextForm.Call("SetTipText", tip.c_str());
oTextForm.Call("SetRequired", required);
oTextForm.Call("SetPlaceholderText", placeholder.c_str());
oTextForm.Call("SetComb", comb);
oTextForm.Call("SetCharactersLimit", maxCharacters);
oTextForm.Call("SetCellWidth", cellWidth);
oTextForm.Call("SetCellWidth", multiLine);
oTextForm.Call("SetMultiline", autoFit);
}
// Main function
int main()
{
// Init DocBuilder
CDocBuilder::Initialize(workDir);
CDocBuilder oBuilder;
oBuilder.SetProperty("--work-directory", workDir);
oBuilder.CreateFile(OFFICESTUDIO_FILE_DOCUMENT_DOCX);
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Create basic form
CValue oDocument = oApi.Call("GetDocument");
CValue oParagraph = oDocument.Call("GetElement", 0);
CValue oHeadingStyle = oDocument.Call("GetStyle", "Heading 3");
oParagraph.Call("AddText", "Employee pass card");
oParagraph.Call("SetStyle", oHeadingStyle);
oDocument.Call("Push", oParagraph);
CValue oPictureForm = oApi.Call("CreatePictureForm");
setPictureFormProperties(oPictureForm, "Photo", "Upload your photo", false, "Photo", "tooBig", true, false, 50, 50, "https://api.onlyoffice.com/content/img/docbuilder/examples/user-profile.png");
oParagraph = oApi.Call("CreateParagraph");
oParagraph.Call("AddElement", oPictureForm);
oDocument.Call("Push", oParagraph);
CValue oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "First name", "Enter your first name", false, "First name", true, 13, 3, false, false);
oParagraph = oApi.Call("CreateParagraph");
oParagraph.Call("AddElement", oTextForm);
oDocument.Call("Push", oParagraph);
// Save and close
oBuilder.SaveFile(OFFICESTUDIO_FILE_DOCUMENT_DOCX, resultPath);
oBuilder.CloseFile();
CDocBuilder::Dispose();
return 0;
}

View File

@ -0,0 +1,156 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include <string>
#include <vector>
#include "common.h"
#include "docbuilder.h"
#include "resources/utils/utils.h"
using namespace std;
using namespace NSDoctRenderer;
const wchar_t* workDir = L"C:\\Program Files\\ONLYOFFICE\\DocumentBuilder";
const wchar_t* resultPath = L"result.pptx";
void addText(CValue oApi, int fontSize, string text, CValue oSlide, CValue oShape, CValue oParagraph, CValue oFill, string jc)
{
CValue oRun = oApi.Call("CreateRun");
CValue oTextPr = oRun.Call("GetTextPr");
oTextPr.Call("SetFontSize", fontSize);
oTextPr.Call("SetFill", oFill);
oTextPr.Call("SetFontFamily", "Tahoma");
oParagraph.Call("SetJc", jc.c_str());
oRun.Call("AddText", text.c_str());
oRun.Call("AddLineBreak");
oParagraph.Call("AddElement", oRun);
oSlide.Call("AddObject", oShape);
}
// Main function
int main()
{
// Init DocBuilder
CDocBuilder::Initialize(workDir);
CDocBuilder oBuilder;
oBuilder.SetProperty("--work-directory", workDir);
// Read chart data from xlsx
wstring templatePath = NSUtils::GetResourcesDirectory() + L"/docs/chart_data.xlsx";
oBuilder.OpenFile(templatePath.c_str(), L"");
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
CValue oWorksheet = oApi.Call("GetActiveSheet");
CValue values = oWorksheet.Call("GetUsedRange").Call("GetValue");
int sizeX = values.GetLength();
int sizeY = values[0].GetLength();
vector<vector<wstring>> data(sizeX, vector<wstring>(sizeY));
for (int i = 0; i < sizeX; i++)
{
for (int j = 0; j < sizeY; j++)
{
data[i][j] = values[i][j].ToString().c_str();
}
}
oBuilder.CloseFile();
// Create chart presentation
oBuilder.CreateFile(OFFICESTUDIO_FILE_PRESENTATION_PPTX);
oContext = oBuilder.GetContext();
oScope = oContext.CreateScope();
oGlobal = oContext.GetGlobal();
oApi = oGlobal["Api"];
CValue oPresentation = oApi.Call("GetPresentation");
CValue oSlide = oPresentation.Call("GetSlideByIndex", 0);
oSlide.Call("RemoveAllObjects");
CValue oRGBColor = oApi.Call("CreateRGBColor", 255, 244, 240);
CValue oFill = oApi.Call("CreateSolidFill", oRGBColor);
oSlide.Call("SetBackground", oFill);
CValue oStroke = oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill"));
CValue oShapeTitle = oApi.Call("CreateShape", "rect", 300 * 36000, 20 * 36000, oApi.Call("CreateNoFill"), oStroke);
CValue oShapeText = oApi.Call("CreateShape", "rect", 120 * 36000, 80 * 36000, oApi.Call("CreateNoFill"), oStroke);
oShapeTitle.Call("SetPosition", 20 * 36000, 20 * 36000);
oShapeText.Call("SetPosition", 210 * 36000, 50 * 36000);
CValue oParagraphTitle = oShapeTitle.Call("GetDocContent").Call("GetElement", 0);
CValue oParagraphText = oShapeText.Call("GetDocContent").Call("GetElement", 0);
oRGBColor = oApi.Call("CreateRGBColor", 115, 81, 68);
oFill = oApi.Call("CreateSolidFill", oRGBColor);
string titleContent = "Price Type Report";
string textContent = "This is an overview of price types. As we can see, May was the price peak, but even in June the price went down, the annual upward trend persists.";
addText(oApi, 80, titleContent, oSlide, oShapeTitle, oParagraphTitle, oFill, "center");
addText(oApi, 42, textContent, oSlide, oShapeText, oParagraphText, oFill, "left");
// Transform 2d array into cols names, rows names and data
CValue cols = oContext.CreateArray(sizeY - 1);
for (int col = 1; col < sizeY; col++)
{
cols[col - 1] = data[0][col].c_str();
}
CValue rows = oContext.CreateArray(sizeX - 1);
for (int row = 1; row < sizeX; row++)
{
rows[row - 1] = data[row][0].c_str();
}
CValue vals = oContext.CreateArray(sizeY - 1);
for (int row = 1; row < sizeY; row++)
{
CValue row_data = oContext.CreateArray(sizeX - 1);
for (int col = 1; col < sizeX; col++)
{
row_data[col - 1] = data[col][row].c_str();
}
vals[row - 1] = row_data;
}
// Pass CValue data to the CreateChart method
CValue oChart = oApi.Call("CreateChart", "lineStacked", vals, cols, rows);
oChart.Call("SetSize", 180 * 36000, 100 * 36000);
oChart.Call("SetPosition", 20 * 36000, 50 * 36000);
oChart.Call("ApplyChartStyle", 24);
oChart.Call("SetLegendFontSize", 12);
oChart.Call("SetLegendPos", "top");
oSlide.Call("AddObject", oChart);
// Save and close
oBuilder.SaveFile(OFFICESTUDIO_FILE_PRESENTATION_PPTX, resultPath);
oBuilder.CloseFile();
CDocBuilder::Dispose();
return 0;
}

View File

@ -0,0 +1,156 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include <map>
#include <string>
#include "common.h"
#include "docbuilder.h"
using namespace std;
using namespace NSDoctRenderer;
const wchar_t* workDir = L"C:\\Program Files\\ONLYOFFICE\\DocumentBuilder";
const wchar_t* resultPath = L"result.pptx";
// Helper functions
CValue createImageSlide(CValue oApi, CValue oPresentation, string image_url)
{
CValue oSlide = oApi.Call("CreateSlide");
oPresentation.Call("AddSlide", oSlide);
CValue oFill = oApi.Call("CreateBlipFill", image_url.c_str(), "stretch");
oSlide.Call("SetBackground", oFill);
oSlide.Call("RemoveAllObjects");
return oSlide;
}
void addTextToSlideShape(CValue oApi, CValue oContent, string text, int fontSize, bool isBold, string js)
{
CValue oParagraph = oApi.Call("CreateParagraph");
oParagraph.Call("SetSpacingBefore", 0);
oParagraph.Call("SetSpacingAfter", 0);
oContent.Call("Push", oParagraph);
CValue oRun = oParagraph.Call("AddText", text.c_str());
oRun.Call("SetFill", oApi.Call("CreateSolidFill", oApi.Call("CreateRGBColor", 0xff, 0xff, 0xff)));
oRun.Call("SetFontSize", fontSize);
oRun.Call("SetFontFamily", "Georgia");
oRun.Call("SetBold", isBold);
oParagraph.Call("SetJc", js.c_str());
}
// Main function
int main()
{
map<string, string>slideImages;
slideImages["gun"] = "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_gun.png";
slideImages["axe"] = "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_axe.png";
slideImages["knight"] = "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_knight.png";
slideImages["sky"] = "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_sky.png";
// Init DocBuilder
CDocBuilder::Initialize(workDir);
CDocBuilder oBuilder;
oBuilder.SetProperty("--work-directory", workDir);
oBuilder.CreateFile(OFFICESTUDIO_FILE_PRESENTATION_PPTX);
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Create presentation
CValue oPresentation = oApi.Call("GetPresentation");
oPresentation.Call("SetSizes", 9144000, 6858000);
CValue oSlide = createImageSlide(oApi, oPresentation, slideImages["gun"]);
oPresentation.Call("GetSlideByIndex", 0).Call("Delete");
CValue oShape = oApi.Call("CreateShape", "rect", 8056800, 3020400, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 608400, 1267200);
CValue oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "How They", 160, true, "left");
addTextToSlideShape(oApi, oContent, "Throw Out", 132, false, "left");
addTextToSlideShape(oApi, oContent, "a Challenge", 132, false, "left");
oSlide.Call("AddObject", oShape);
oSlide = createImageSlide(oApi, oPresentation, slideImages["axe"]);
oShape = oApi.Call("CreateShape", "rect", 6904800, 1724400, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 1764000, 1191600);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "American Indians ", 110, true, "right");
addTextToSlideShape(oApi, oContent, "(XVII century)", 94, false, "right");
oSlide.Call("AddObject", oShape);
oShape = oApi.Call("CreateShape", "rect", 4986000, 2419200, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 3834000, 3888000);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "put a tomahawk on the ground in the ", 84, false, "right");
addTextToSlideShape(oApi, oContent, "rival's camp", 84, false, "right");
oSlide.Call("AddObject", oShape);
oSlide = createImageSlide(oApi, oPresentation, slideImages["knight"]);
oShape = oApi.Call("CreateShape", "rect", 6904800, 1724400, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 1764000, 1191600);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "European Knights", 110, true, "right");
addTextToSlideShape(oApi, oContent, " (XII-XVI centuries)", 94, false, "right");
oSlide.Call("AddObject", oShape);
oShape = oApi.Call("CreateShape", "rect", 4986000, 2419200, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 3834000, 3888000);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "threw a glove", 84, false, "right");
addTextToSlideShape(oApi, oContent, "in the rival's face", 84, false, "right");
oSlide.Call("AddObject", oShape);
oSlide = createImageSlide(oApi, oPresentation, slideImages["sky"]);
oShape = oApi.Call("CreateShape", "rect", 7887600, 3063600, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 630000, 1357200);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "OnlyOffice", 176, false, "center");
addTextToSlideShape(oApi, oContent, "stands for Peace", 132, false, "center");
oSlide.Call("AddObject", oShape);
// Save and close
oBuilder.SaveFile(OFFICESTUDIO_FILE_PRESENTATION_PPTX, resultPath);
oBuilder.CloseFile();
CDocBuilder::Dispose();
return 0;
}

View File

@ -0,0 +1,94 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include <map>
#include <string>
#include "common.h"
#include "docbuilder.h"
#include "resources/utils/utils.h"
using namespace std;
using namespace NSDoctRenderer;
const wchar_t* workDir = L"C:\\Program Files\\ONLYOFFICE\\DocumentBuilder";
const wchar_t* resultPath = L"result.docx";
// Main function
int main()
{
std::map<wstring, wstring> formData;
formData[L"Photo"] = L"https://api.onlyoffice.com/content/img/docbuilder/examples/blue_cloud.png";
formData[L"Serial"] = L"A1345";
formData[L"Company Name"] = L"Blue Cloud";
formData[L"Date"] = L"25.12.2023";
formData[L"Recipient"] = L"Space Corporation";
formData[L"Qty1"] = L"25";
formData[L"Description1"] = L"Frame";
formData[L"Qty2"] = L"2";
formData[L"Description2"] = L"Stack";
formData[L"Qty3"] = L"34";
formData[L"Description3"] = L"Shifter";
// Init DocBuilder
CDocBuilder::Initialize(workDir);
CDocBuilder oBuilder;
oBuilder.SetProperty("--work-directory", workDir);
wstring templatePath = NSUtils::GetResourcesDirectory() + L"/docs/form.docx";
oBuilder.OpenFile(templatePath.c_str(), L"");
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Fill form
CValue oDocument = oApi.Call("GetDocument");
CValue aForms = oDocument.Call("GetAllForms");
int formNum = 0;
while (formNum < (int)aForms.GetLength())
{
CValue form = aForms[formNum];
wstring type = aForms[formNum].Call("GetFormType").ToString().c_str();
wstring value = formData[aForms[formNum].Call("GetFormKey").ToString().c_str()];
if (type == L"textForm") form.Call("SetText", value.c_str());
if (type == L"pictureForm") form.Call("SetImage", value.c_str());
formNum++;
}
// Save and close
oBuilder.SaveFile(OFFICESTUDIO_FILE_DOCUMENT_DOCX, resultPath);
oBuilder.CloseFile();
CDocBuilder::Dispose();
return 0;
}

View File

@ -0,0 +1,100 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#include <string>
#include "common.h"
#include "docbuilder.h"
using namespace std;
using namespace NSDoctRenderer;
const wchar_t* workDir = L"C:\\Program Files\\ONLYOFFICE\\DocumentBuilder";
const wchar_t* resultPath = L"result.xlsx";
// Main function
int main()
{
string data[9][4] = {
{ "Id", "Product", "Price", "Available" },
{ "1001", "Item A", "12.2", "true" },
{ "1002", "Item B", "18.8", "true" },
{ "1003", "Item C", "70.1", "false" },
{ "1004", "Item D", "60.6", "true" },
{ "1005", "Item E", "32.6", "true" },
{ "1006", "Item F", "28.3", "false" },
{ "1007", "Item G", "11.1", "false" },
{ "1008", "Item H", "41.4", "true" }
};
// Init DocBuilder
CDocBuilder::Initialize(workDir);
CDocBuilder oBuilder;
oBuilder.SetProperty("--work-directory", workDir);
oBuilder.CreateFile(OFFICESTUDIO_FILE_SPREADSHEET_XLSX);
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Find and comment formula errors
CValue oWorksheet = oApi.Call("GetActiveSheet");
// Create CValue array from data
int rowsLen = sizeof data / sizeof data[0];
int colsLen = sizeof data[0] / sizeof(string);
CValue oArray = oContext.CreateArray(rowsLen);
for (int row = 0; row < rowsLen; row++)
{
CValue oArrayCol = oContext.CreateArray(colsLen);
for (int col = 0; col < colsLen; col++)
{
oArrayCol[col] = data[row][col].c_str();
}
oArray[row] = oArrayCol;
}
// First cell in the range (A1) is equal to (0,0)
CValue startCell = oWorksheet.Call("GetRangeByNumber", 0, 0);
// Last cell in the range is equal to array length -1
CValue endCell = oWorksheet.Call("GetRangeByNumber", oArray.GetLength() - 1, oArray[0].GetLength() - 1);
oWorksheet.Call("GetRange", startCell, endCell).Call("SetValue", oArray);
// Save and close
oBuilder.SaveFile(OFFICESTUDIO_FILE_SPREADSHEET_XLSX, resultPath);
oBuilder.CloseFile();
CDocBuilder::Dispose();
return 0;
}

View File

@ -0,0 +1,98 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
using docbuilder_net;
using OfficeFileTypes = docbuilder_net.FileTypes;
using CValue = docbuilder_net.CDocBuilderValue;
using CContext = docbuilder_net.CDocBuilderContext;
using CContextScope = docbuilder_net.CDocBuilderContextScope;
namespace Sample
{
public class CommentingErrors
{
public static void Main(string[] args)
{
string workDirectory = "C:/Program Files/ONLYOFFICE/DocumentBuilder";
string resultPath = "../../../result.xlsx";
string filePath = "../../../../../../resources/docs/spreadsheet_with_errors.xlsx";
// add Docbuilder dlls in path
System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + workDirectory);
CommentErrors(workDirectory, resultPath, filePath);
}
public static void CommentErrors(string workDirectory, string resultPath, string filePath)
{
var doctype = (int)OfficeFileTypes.Spreadsheet.XLSX;
// Init DocBuilder
CDocBuilder.Initialize(workDirectory);
CDocBuilder oBuilder = new CDocBuilder();
oBuilder.OpenFile(filePath, "xlsx");
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Find and comment formula errors
CValue oWorksheet = oApi.Call("GetActiveSheet");
CValue oRange = oWorksheet.Call("GetUsedRange");
var data = oRange.Call("GetValue");
for (int row = 0; row < data.GetLength(); row++)
{
for (int col = 0; col < data[0].GetLength(); col++)
{
CheckCell(oWorksheet, data[row][col].ToString(), row, col);
}
}
// Save file and close DocBuilder
oBuilder.SaveFile(doctype, resultPath);
oBuilder.CloseFile();
CDocBuilder.Destroy();
}
public static void CheckCell(CValue oWorksheet, string cell, int row, int col)
{
if (cell.Contains("#"))
{
string comment = "Error" + cell;
CValue errorCell = oWorksheet.Call("GetRangeByNumber", row, col);
errorCell.Call("AddComment", comment);
}
}
}
}

View File

@ -0,0 +1,212 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
using docbuilder_net;
using OfficeFileTypes = docbuilder_net.FileTypes;
using CValue = docbuilder_net.CDocBuilderValue;
using CContext = docbuilder_net.CDocBuilderContext;
using CContextScope = docbuilder_net.CDocBuilderContextScope;
namespace Sample
{
public class CreatingAdvancedForm
{
public static void Main(string[] args)
{
string workDirectory = "C:/Program Files/ONLYOFFICE/DocumentBuilder";
string resultPath = "../../../result.docx";
// add Docbuilder dlls in path
System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + workDirectory);
CreateAdvancedForm(workDirectory, resultPath);
}
public static void CreateAdvancedForm(string workDirectory, string resultPath)
{
var doctype = (int)OfficeFileTypes.Document.DOCX;
// Init DocBuilder
CDocBuilder.Initialize(workDirectory);
CDocBuilder oBuilder = new CDocBuilder();
oBuilder.CreateFile(doctype);
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Create advanced form
CValue oDocument = oApi.Call("GetDocument");
CValue oTable = createFullWidthTable(oApi, 1, 2, 255);
CValue oParagraph = getTableCellParagraph(oTable, 0, 0);
addTextToParagraph(oParagraph, "PURCHASE ORDER", 36, true);
oParagraph = getTableCellParagraph(oTable, 0, 1);
addTextToParagraph(oParagraph, "Serial # ", 25, true);
CValue oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "Serial", "Enter serial number", false, "Serial", true, 6, 1, false, false);
addTextFormToParagraph(oParagraph, oTextForm, 25, "left", true, 255);
oDocument.Call("Push", oTable);
CValue oPictureForm = oApi.Call("CreatePictureForm");
setPictureFormProperties(oPictureForm, "Photo", "Upload company logo", false, "Photo", "tooBig", false, false, 0, 0, "https://api.onlyoffice.com/content/img/docbuilder/examples/user-profile.png");
oParagraph = oApi.Call("CreateParagraph");
oParagraph.Call("AddElement", oPictureForm);
oDocument.Call("Push", oParagraph);
oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "Company Name", "Enter company name", false, "Company Name", true, 20, 1, false, false);
oParagraph = oApi.Call("CreateParagraph");
addTextFormToParagraph(oParagraph, oTextForm, 35, "left", false, 255);
oDocument.Call("Push", oParagraph);
oParagraph = oApi.Call("CreateParagraph");
addTextToParagraph(oParagraph, "Date: ", 25, true);
oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "Date", "Date", false, "DD.MM.YYYY", true, 10, 1, false, false);
addTextFormToParagraph(oParagraph, oTextForm, 25, "left", true, 255);
oDocument.Call("Push", oParagraph);
oParagraph = oApi.Call("CreateParagraph");
addTextToParagraph(oParagraph, "To:", 35, true);
oDocument.Call("Push", oParagraph);
oTable = createFullWidthTable(oApi, 1, 1, 200);
oParagraph = getTableCellParagraph(oTable, 0, 0);
oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "Recipient", "Recipient", false, "Recipient", true, 25, 1, false, false);
addTextFormToParagraph(oParagraph, oTextForm, 32, "left", false, 255);
oDocument.Call("Push", oTable);
oTable = createFullWidthTable(oApi, 10, 2, 200);
oTable.Call("GetRow", 0).Call("SetBackgroundColor", 245, 245, 245, false);
CValue oCell = oTable.Call("GetCell", 0, 0);
oCell.Call("SetWidth", "percent", 30);
oParagraph = getTableCellParagraph(oTable, 0, 0);
addTextToParagraph(oParagraph, "Qty.", 30, true);
oParagraph = getTableCellParagraph(oTable, 0, 1);
addTextToParagraph(oParagraph, "Description", 30, true);
for (var i = 1; i < 10; i++)
{
CValue oTempParagraph = getTableCellParagraph(oTable, i, 0);
CValue oTempTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTempTextForm, "Qty" + i, "Qty" + i, false, " ", true, 9, 1, false, false);
addTextFormToParagraph(oTempParagraph, oTempTextForm, 30, "left", false, 255);
oTempParagraph = getTableCellParagraph(oTable, i, 1);
oTempTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTempTextForm, "Description" + i, "Description" + i, false, " ", true, 22, 1, false, false);
addTextFormToParagraph(oTempParagraph, oTempTextForm, 30, "left", false, 255);
}
oDocument.Call("Push", oTable);
oDocument.Call("RemoveElement", 0);
oDocument.Call("RemoveElement", 1);
// Save file and close DocBuilder
oBuilder.SaveFile(doctype, resultPath);
oBuilder.CloseFile();
CDocBuilder.Destroy();
}
public static CValue createFullWidthTable(CValue oApi, int rows, int cols, int borderColor)
{
CValue oTable = oApi.Call("CreateTable", cols, rows);
oTable.Call("SetWidth", "percent", 100);
setTableBorders(oTable, borderColor);
return oTable;
}
public static void setTableBorders(CValue oTable, int borderColor)
{
oTable.Call("SetTableBorderTop", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderBottom", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderLeft", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderRight", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderInsideV", "single", 4, 0, borderColor, borderColor, borderColor);
oTable.Call("SetTableBorderInsideH", "single", 4, 0, borderColor, borderColor, borderColor);
}
public static CValue getTableCellParagraph(CValue oTable, int row, int col)
{
return oTable.Call("GetCell", row, col).Call("GetContent").Call("GetElement", 0);
}
public static void addTextToParagraph(CValue oParagraph, string text, int fontSize, bool isBold)
{
oParagraph.Call("AddText", text);
oParagraph.Call("SetFontSize", fontSize);
oParagraph.Call("SetBold", isBold);
}
public static void setPictureFormProperties(CValue oPictureForm, string key, string tip, bool required, string placeholder, string scaleFlag, bool lockAspectRatio, bool respectBorders, int shiftX, int shiftY, string imageUrl)
{
oPictureForm.Call("SetFormKey", key);
oPictureForm.Call("SetTipText", tip);
oPictureForm.Call("SetRequired", required);
oPictureForm.Call("SetPlaceholderText", placeholder);
oPictureForm.Call("SetScaleFlag", scaleFlag);
oPictureForm.Call("SetLockAspectRatio", lockAspectRatio);
oPictureForm.Call("SetRespectBorders", respectBorders);
oPictureForm.Call("SetPicturePosition", shiftX, shiftY);
oPictureForm.Call("SetImage", imageUrl);
}
public static void setTextFormProperties(CValue oTextForm, string key, string tip, bool required, string placeholder, bool comb, int maxCharacters, int cellWidth, bool multiLine, bool autoFit)
{
oTextForm.Call("SetFormKey", key);
oTextForm.Call("SetTipText", tip);
oTextForm.Call("SetRequired", required);
oTextForm.Call("SetPlaceholderText", placeholder);
oTextForm.Call("SetComb", comb);
oTextForm.Call("SetCharactersLimit", maxCharacters);
oTextForm.Call("SetCellWidth", cellWidth);
oTextForm.Call("SetCellWidth", multiLine);
oTextForm.Call("SetMultiline", autoFit);
}
public static void addTextFormToParagraph(CValue oParagraph, CValue oTextForm, int fontSize, string jc, bool hasBorder, int borderColor)
{
if (hasBorder)
{
oTextForm.Call("SetBorderColor", borderColor, borderColor, borderColor);
}
oParagraph.Call("AddElement", oTextForm);
oParagraph.Call("SetFontSize", fontSize);
oParagraph.Call("SetJc", jc);
}
}
}

View File

@ -0,0 +1,123 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
using docbuilder_net;
using OfficeFileTypes = docbuilder_net.FileTypes;
using CValue = docbuilder_net.CDocBuilderValue;
using CContext = docbuilder_net.CDocBuilderContext;
using CContextScope = docbuilder_net.CDocBuilderContextScope;
namespace Sample
{
public class CreatingBasicForm
{
public static void Main(string[] args)
{
string workDirectory = "C:/Program Files/ONLYOFFICE/DocumentBuilder";
string resultPath = "../../../result.docx";
// add Docbuilder dlls in path
System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + workDirectory);
CreateBasicForm(workDirectory, resultPath);
}
public static void CreateBasicForm(string workDirectory, string resultPath)
{
var doctype = (int)OfficeFileTypes.Document.DOCX;
// Init DocBuilder
CDocBuilder.Initialize(workDirectory);
CDocBuilder oBuilder = new CDocBuilder();
oBuilder.CreateFile(doctype);
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Create basic form
CValue oDocument = oApi.Call("GetDocument");
CValue oParagraph = oDocument.Call("GetElement", 0);
CValue oHeadingStyle = oDocument.Call("GetStyle", "Heading 3");
oParagraph.Call("AddText", "Employee pass card");
oParagraph.Call("SetStyle", oHeadingStyle);
oDocument.Call("Push", oParagraph);
CValue oPictureForm = oApi.Call("CreatePictureForm");
setPictureFormProperties(oPictureForm, "Photo", "Upload your photo", false, "Photo", "tooBig", true, false, 50, 50, "https://api.onlyoffice.com/content/img/docbuilder/examples/user-profile.png");
oParagraph = oApi.Call("CreateParagraph");
oParagraph.Call("AddElement", oPictureForm);
oDocument.Call("Push", oParagraph);
CValue oTextForm = oApi.Call("CreateTextForm");
setTextFormProperties(oTextForm, "First name", "Enter your first name", false, "First name", true, 13, 3, false, false);
oParagraph = oApi.Call("CreateParagraph");
oParagraph.Call("AddElement", oTextForm);
oDocument.Call("Push", oParagraph);
// Save file and close DocBuilder
oBuilder.SaveFile(doctype, resultPath);
oBuilder.CloseFile();
CDocBuilder.Destroy();
}
public static void setPictureFormProperties(CValue oPictureForm, string key, string tip, bool required, string placeholder, string scaleFlag, bool lockAspectRatio, bool respectBorders, int shiftX, int shiftY, string imageUrl)
{
oPictureForm.Call("SetFormKey", key);
oPictureForm.Call("SetTipText", tip);
oPictureForm.Call("SetRequired", required);
oPictureForm.Call("SetPlaceholderText", placeholder);
oPictureForm.Call("SetScaleFlag", scaleFlag);
oPictureForm.Call("SetLockAspectRatio", lockAspectRatio);
oPictureForm.Call("SetRespectBorders", respectBorders);
oPictureForm.Call("SetPicturePosition", shiftX, shiftY);
oPictureForm.Call("SetImage", imageUrl);
}
public static void setTextFormProperties(CValue oTextForm, string key, string tip, bool required, string placeholder, bool comb, int maxCharacters, int cellWidth, bool multiLine, bool autoFit)
{
oTextForm.Call("SetFormKey", key);
oTextForm.Call("SetTipText", tip);
oTextForm.Call("SetRequired", required);
oTextForm.Call("SetPlaceholderText", placeholder);
oTextForm.Call("SetComb", comb);
oTextForm.Call("SetCharactersLimit", maxCharacters);
oTextForm.Call("SetCellWidth", cellWidth);
oTextForm.Call("SetCellWidth", multiLine);
oTextForm.Call("SetMultiline", autoFit);
}
}
}

View File

@ -0,0 +1,196 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
using docbuilder_net;
using OfficeFileTypes = docbuilder_net.FileTypes;
using CValue = docbuilder_net.CDocBuilderValue;
using CContext = docbuilder_net.CDocBuilderContext;
using CContextScope = docbuilder_net.CDocBuilderContextScope;
namespace Sample
{
public class CreatingChartPresentation
{
public static void Main(string[] args)
{
string workDirectory = "C:/Program Files/ONLYOFFICE/DocumentBuilder";
string resultPath = "../../../result.pptx";
string filePath = "../../../../../../resources/docs/chart_data.xlsx";
// add Docbuilder dlls in path
System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + workDirectory);
CreateChartPresentation(workDirectory, resultPath, filePath);
}
public static void CreateChartPresentation(string workDirectory, string resultPath, string filePath)
{
var doctype = (int)OfficeFileTypes.Presentation.PPTX;
// Init DocBuilder
CDocBuilder.Initialize(workDirectory);
CDocBuilder oBuilder = new CDocBuilder();
// Read chart data from xlsx
oBuilder.OpenFile(filePath, "xlsx");
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
CValue oWorksheet = oApi.Call("GetActiveSheet");
CValue oRange = oWorksheet.Call("GetUsedRange").Call("GetValue");
object[,] array = oRangeTo2dArray(oRange, oContext);
oBuilder.CloseFile();
// Create chart presentation
oBuilder.CreateFile(doctype);
oContext = oBuilder.GetContext();
oScope = oContext.CreateScope();
oGlobal = oContext.GetGlobal();
oApi = oGlobal["Api"];
CValue oPresentation = oApi.Call("GetPresentation");
CValue oSlide = oPresentation.Call("GetSlideByIndex", 0);
oSlide.Call("RemoveAllObjects");
CValue oRGBColor = oApi.Call("CreateRGBColor", 255, 244, 240);
CValue oFill = oApi.Call("CreateSolidFill", oRGBColor);
oSlide.Call("SetBackground", oFill);
CValue oStroke = oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill"));
CValue oShapeTitle = oApi.Call("CreateShape", "rect", 300 * 36000, 20 * 36000, oApi.Call("CreateNoFill"), oStroke);
CValue oShapeText = oApi.Call("CreateShape", "rect", 120 * 36000, 80 * 36000, oApi.Call("CreateNoFill"), oStroke);
oShapeTitle.Call("SetPosition", 20 * 36000, 20 * 36000);
oShapeText.Call("SetPosition", 210 * 36000, 50 * 36000);
CValue oParagraphTitle = oShapeTitle.Call("GetDocContent").Call("GetElement", 0);
CValue oParagraphText = oShapeText.Call("GetDocContent").Call("GetElement", 0);
oRGBColor = oApi.Call("CreateRGBColor", 115, 81, 68);
oFill = oApi.Call("CreateSolidFill", oRGBColor);
string titleContent = "Price Type Report";
string textContent = "This is an overview of price types. As we can see, May was the price peak, but even in June the price went down, the annual upward trend persists.";
addText(oApi, 80, titleContent, oSlide, oShapeTitle, oParagraphTitle, oFill, "center");
addText(oApi, 42, textContent, oSlide, oShapeText, oParagraphText, oFill, "left");
// Transform 2d array into cols names, rows names and data
CValue array_cols = colsFromArray(array, oContext);
CValue array_rows = rowsFromArray(array, oContext);
CValue array_data = dataFromArray(array, oContext);
// Pass CValue data to the CreateChart method
CValue oChart = oApi.Call("CreateChart", "lineStacked", array_data, array_cols, array_rows);
oChart.Call("SetSize", 180 * 36000, 100 * 36000);
oChart.Call("SetPosition", 20 * 36000, 50 * 36000);
oChart.Call("ApplyChartStyle", 24);
oChart.Call("SetVertAxisLabelsFontSize", 16);
oChart.Call("SetHorAxisLabelsFontSize", 16);
oChart.Call("SetLegendFontSize", 16);
oChart.Call("SetLegendPos", "top");
oSlide.Call("AddObject", oChart);
// Save file and close DocBuilder
oBuilder.SaveFile(doctype, resultPath);
oBuilder.CloseFile();
CDocBuilder.Destroy();
}
public static object[,] oRangeTo2dArray(CValue oRange, CContext oContext)
{
int rowsLen = (int)oRange.GetLength();
int colsLen = (int)oRange[0].GetLength();
object[,] oArray = new object[rowsLen, colsLen];
for (int col = 0; col < colsLen; col++)
{
CValue oArrayRow = oContext.CreateArray(rowsLen);
for (int row = 0; row < rowsLen; row++)
{
oArray[row, col] = oRange[row][col].ToString();
}
}
return oArray;
}
public static CValue colsFromArray(object[,] array, CContext oContext)
{
int colsLen = array.GetLength(1) - 1;
CValue cols = oContext.CreateArray(colsLen);
for (int col = 1; col <= colsLen; col++)
{
cols[col - 1] = array[0, col].ToString();
}
return cols;
}
public static CValue rowsFromArray(object[,] array, CContext oContext)
{
int rowsLen = array.GetLength(0) - 1;
CValue rows = oContext.CreateArray(rowsLen);
for (int row = 1; row <= rowsLen; row++)
{
rows[row - 1] = array[row, 0].ToString();
}
return rows;
}
public static CValue dataFromArray(object[,] array, CContext oContext)
{
int colsLen = array.GetLength(0) - 1;
int rowsLen = array.GetLength(1) - 1;
CValue data = oContext.CreateArray(rowsLen);
for (int row = 1; row <= rowsLen; row++)
{
CValue row_data = oContext.CreateArray(colsLen);
for (int col = 1; col <= colsLen; col++)
{
row_data[col - 1] = array[col, row].ToString();
}
data[row - 1] = row_data;
}
return data;
}
public static void addText(CValue oApi, int fontSize, string text, CValue oSlide, CValue oShape, CValue oParagraph, CValue oFill, string jc)
{
CValue oRun = oApi.Call("CreateRun");
var oTextPr = oRun.Call("GetTextPr");
oTextPr.Call("SetFontSize", fontSize);
oTextPr.Call("SetFill", oFill);
oTextPr.Call("SetFontFamily", "Tahoma");
oParagraph.Call("SetJc", jc);
oRun.Call("AddText", text);
oRun.Call("AddLineBreak");
oParagraph.Call("AddElement", oRun);
oSlide.Call("AddObject", oShape);
}
}
}

View File

@ -0,0 +1,168 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
using docbuilder_net;
using OfficeFileTypes = docbuilder_net.FileTypes;
using CValue = docbuilder_net.CDocBuilderValue;
using CContext = docbuilder_net.CDocBuilderContext;
using CContextScope = docbuilder_net.CDocBuilderContextScope;
using System.Collections.Generic;
namespace Sample
{
public class CreatingPresentation
{
public static void Main(string[] args)
{
string workDirectory = "C:/Program Files/ONLYOFFICE/DocumentBuilder";
string resultPath = "../../../result.pptx";
IDictionary<string, string> slideImages = new Dictionary<string, string>() {
{ "gun", "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_gun.png" },
{ "axe","https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_axe.png" },
{ "knight", "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_knight.png" },
{ "sky","https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_sky.png" }
};
// add Docbuilder dlls in path
System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + workDirectory);
CreatePresentation(workDirectory, resultPath, slideImages);
}
public static void CreatePresentation(string workDirectory, string resultPath, IDictionary<string, string> slideImages)
{
var doctype = (int)OfficeFileTypes.Presentation.PPTX;
// Init DocBuilder
CDocBuilder.Initialize(workDirectory);
CDocBuilder oBuilder = new CDocBuilder();
// Create presentation
oBuilder.CreateFile(doctype);
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
CValue oPresentation = oApi.Call("GetPresentation");
oPresentation.Call("SetSizes", 9144000, 6858000);
CValue oSlide = createImageSlide(oApi, oPresentation, slideImages["gun"]);
oPresentation.Call("GetSlideByIndex", 0).Call("Delete");
CValue oShape = oApi.Call("CreateShape", "rect", 8056800, 3020400, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 608400, 1267200);
CValue oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "How They", 160, true, "left");
addTextToSlideShape(oApi, oContent, "Throw Out", 132, false, "left");
addTextToSlideShape(oApi, oContent, "a Challenge", 132, false, "left");
oSlide.Call("AddObject", oShape);
oSlide = createImageSlide(oApi, oPresentation, slideImages["axe"]);
oShape = oApi.Call("CreateShape", "rect", 6904800, 1724400, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 1764000, 1191600);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "American Indians ", 110, true, "right");
addTextToSlideShape(oApi, oContent, "(XVII century)", 94, false, "right");
oSlide.Call("AddObject", oShape);
oShape = oApi.Call("CreateShape", "rect", 4986000, 2419200, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 3834000, 3888000);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "put a tomahawk on the ground in the ", 84, false, "right");
addTextToSlideShape(oApi, oContent, "rival's camp", 84, false, "right");
oSlide.Call("AddObject", oShape);
oSlide = createImageSlide(oApi, oPresentation, slideImages["knight"]);
oShape = oApi.Call("CreateShape", "rect", 6904800, 1724400, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 1764000, 1191600);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "European Knights", 110, true, "right");
addTextToSlideShape(oApi, oContent, " (XII-XVI centuries)", 94, false, "right");
oSlide.Call("AddObject", oShape);
oShape = oApi.Call("CreateShape", "rect", 4986000, 2419200, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 3834000, 3888000);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "threw a glove", 84, false, "right");
addTextToSlideShape(oApi, oContent, "in the rival's face", 84, false, "right");
oSlide.Call("AddObject", oShape);
oSlide = createImageSlide(oApi, oPresentation, slideImages["sky"]);
oShape = oApi.Call("CreateShape", "rect", 7887600, 3063600, oApi.Call("CreateNoFill"), oApi.Call("CreateStroke", 0, oApi.Call("CreateNoFill")));
oShape.Call("SetPosition", 630000, 1357200);
oContent = oShape.Call("GetDocContent");
oContent.Call("RemoveAllElements");
addTextToSlideShape(oApi, oContent, "OnlyOffice", 176, false, "center");
addTextToSlideShape(oApi, oContent, "stands for Peace", 132, false, "center");
oSlide.Call("AddObject", oShape);
// Save file and close DocBuilder
oBuilder.SaveFile(doctype, resultPath);
oBuilder.CloseFile();
CDocBuilder.Destroy();
}
public static CValue createImageSlide(CValue oApi, CValue oPresentation, string image_url)
{
CValue oSlide = oApi.Call("CreateSlide");
oPresentation.Call("AddSlide", oSlide);
var oFill = oApi.Call("CreateBlipFill", image_url, "stretch");
oSlide.Call("SetBackground", oFill);
oSlide.Call("RemoveAllObjects");
return oSlide;
}
public static void addTextToSlideShape(CValue oApi, CValue oContent, string text, int fontSize, bool isBold, string js)
{
var oParagraph = oApi.Call("CreateParagraph");
oParagraph.Call("SetSpacingBefore", 0);
oParagraph.Call("SetSpacingAfter", 0);
oContent.Call("Push", oParagraph);
var oRun = oParagraph.Call("AddText", text);
oRun.Call("SetFill", oApi.Call("CreateSolidFill", oApi.Call("CreateRGBColor", 0xff, 0xff, 0xff)));
oRun.Call("SetFontSize", fontSize);
oRun.Call("SetFontFamily", "Georgia");
oRun.Call("SetBold", isBold);
oParagraph.Call("SetJc", js);
}
}
}

View File

@ -0,0 +1,115 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
using docbuilder_net;
using OfficeFileTypes = docbuilder_net.FileTypes;
using CValue = docbuilder_net.CDocBuilderValue;
using CContext = docbuilder_net.CDocBuilderContext;
using CContextScope = docbuilder_net.CDocBuilderContextScope;
using System;
using System.Collections.Generic;
namespace Sample
{
public class FillingForm
{
public static void Main(string[] args)
{
string workDirectory = "C:/Program Files/ONLYOFFICE/DocumentBuilder";
string filePath = "../../../../../../resources/docs/form.docx";
string resultPath = "../../../result.docx";
IDictionary<string, string> formData = new Dictionary<string, string>() {
{ "Photo", "https://api.onlyoffice.com/content/img/docbuilder/examples/blue_cloud.png" },
{ "Serial","A1345" },
{ "Company Name", "Blue Cloud" },
{ "Date", "25.12.2023" },
{ "Recipient", "Space Corporation" },
{ "Qty1", "25" },
{ "Description1", "Frame" },
{ "Qty2", "2" },
{ "Description2", "Stack" },
{ "Qty3", "34" },
{ "Description3", "Shifter" }
};
// add Docbuilder dlls in path
System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + workDirectory);
FillForm(workDirectory, resultPath, filePath, formData);
}
public static void FillForm(string workDirectory, string resultPath, string filePath, IDictionary<string, string> formData)
{
var doctype = (int)OfficeFileTypes.Document.DOCX;
// Init DocBuilder
CDocBuilder.Initialize(workDirectory);
CDocBuilder oBuilder = new CDocBuilder();
oBuilder.OpenFile(filePath, "docxf");
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
// Fill form
CValue oDocument = oApi.Call("GetDocument");
CValue aForms = oDocument.Call("GetAllForms");
int formNum = 0;
while (formNum < aForms.GetLength())
{
CValue form = aForms[formNum];
string type = form.Call("GetFormType").ToString();
string value;
try
{
value = formData[form.Call("GetFormKey").ToString()];
}
catch (Exception e)
{
value = "";
}
if (type == "textForm") form.Call("SetText", value);
if (type == "pictureForm") form.Call("SetImage", value);
formNum++;
}
// Save file and close DocBuilder
oBuilder.SaveFile(doctype, resultPath);
oBuilder.CloseFile();
CDocBuilder.Destroy();
}
}
}

View File

@ -0,0 +1,114 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
using docbuilder_net;
using OfficeFileTypes = docbuilder_net.FileTypes;
using CValue = docbuilder_net.CDocBuilderValue;
using CContext = docbuilder_net.CDocBuilderContext;
using CContextScope = docbuilder_net.CDocBuilderContextScope;
namespace Sample
{
public class FillingSpreadsheet
{
public static void Main(string[] args)
{
string workDirectory = "C:/Program Files/ONLYOFFICE/DocumentBuilder";
string resultPath = "../../../result.xlsx";
object[,] data = {
{ "Id", "Product", "Price", "Available"},
{ 1001, "Item A", 12.2, true },
{ 1002, "Item B", 18.8, true },
{ 1003, "Item C", 70.1, false },
{ 1004, "Item D", 60.6, true },
{ 1005, "Item E", 32.6, true },
{ 1006, "Item F", 28.3, false },
{ 1007, "Item G", 11.1, false },
{ 1008, "Item H", 41.4, true }
};
// add Docbuilder dlls in path
System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + workDirectory);
FillSpreadsheet(workDirectory, resultPath, data);
}
public static void FillSpreadsheet(string workDirectory, string resultPath, object[,] data)
{
var doctype = (int)OfficeFileTypes.Spreadsheet.XLSX;
// Init DocBuilder
CDocBuilder.Initialize(workDirectory);
CDocBuilder oBuilder = new CDocBuilder();
oBuilder.CreateFile(doctype);
CContext oContext = oBuilder.GetContext();
CContextScope oScope = oContext.CreateScope();
CValue oGlobal = oContext.GetGlobal();
CValue oApi = oGlobal["Api"];
CValue oWorksheet = oApi.Call("GetActiveSheet");
// pass data
CValue oArray = TwoDimArrayToCValue(data, oContext);
// First cell in the range (A1) is equal to (0,0)
CValue startCell = oWorksheet.Call("GetRangeByNumber", 0, 0);
// Last cell in the range is equal to array length -1
CValue endCell = oWorksheet.Call("GetRangeByNumber", oArray.GetLength() - 1, oArray[0].GetLength() - 1);
oWorksheet.Call("GetRange", startCell, endCell).Call("SetValue", oArray);
// Save file and close DocBuilder
oBuilder.SaveFile(doctype, resultPath);
oBuilder.CloseFile();
CDocBuilder.Destroy();
}
public static CValue TwoDimArrayToCValue(object[,] data, CContext oContext)
{
int rowsLen = data.GetLength(0);
int colsLen = data.GetLength(1);
CValue oArray = oContext.CreateArray(rowsLen);
for (int row = 0; row < rowsLen; row++)
{
CValue oArrayCol = oContext.CreateArray(colsLen);
for (int col = 0; col < colsLen; col++)
{
oArrayCol[col] = data[row, col].ToString();
}
oArray[row] = oArrayCol;
}
return oArray;
}
}
}

View File

@ -0,0 +1,76 @@
import docbuilder.*;
public class Program {
public static void main(String[] args) {
String resultPath = "result.docx";
createBasicForm(resultPath);
// Need to explicitly call System.gc() to free up resources
System.gc();
}
public static void createBasicForm(String resultPath) {
int doctype = FileTypes.Document.DOCX;
// Initialize builder with docbuilder.jar directory by passing empty string
CDocBuilder.initialize("");
CDocBuilder builder = new CDocBuilder();
builder.createFile(doctype);
CDocBuilderContext context = builder.getContext();
CDocBuilderValue global = context.getGlobal();
CDocBuilderValue api = global.get("Api");
// Create basic form
CDocBuilderValue document = api.call("GetDocument");
CDocBuilderValue paragraph = document.call("GetElement", 0);
CDocBuilderValue headingStyle = document.call("GetStyle", "Heading 3");
paragraph.call("AddText", "Employee pass card");
paragraph.call("SetStyle", headingStyle);
document.call("Push", paragraph);
CDocBuilderValue pictureForm = api.call("CreatePictureForm");
setPictureFormProperties(pictureForm, "Photo", "Upload your photo", false, "Photo", "tooBig", true, false, 50, 50, "https://api.onlyoffice.com/content/img/docbuilder/examples/user-profile.png");
paragraph = api.call("CreateParagraph");
paragraph.call("AddElement", pictureForm);
document.call("Push", paragraph);
CDocBuilderValue textForm = api.call("CreateTextForm");
setTextFormProperties(textForm, "First name", "Enter your first name", false, "First name", true, 13, 3, false, false);
paragraph = api.call("CreateParagraph");
paragraph.call("AddElement", textForm);
document.call("Push", paragraph);
// Save file and close DocBuilder
builder.saveFile(doctype, resultPath);
builder.closeFile();
CDocBuilder.dispose();
}
public static void setPictureFormProperties(CDocBuilderValue pictureForm, String key, String tip, boolean required, String placeholder, String scaleFlag, boolean lockAspectRatio, boolean respectBorders, int shiftX, int shiftY, String imageUrl) {
pictureForm.call("SetFormKey", key);
pictureForm.call("SetTipText", tip);
pictureForm.call("SetRequired", required);
pictureForm.call("SetPlaceholderText", placeholder);
pictureForm.call("SetScaleFlag", scaleFlag);
pictureForm.call("SetLockAspectRatio", lockAspectRatio);
pictureForm.call("SetRespectBorders", respectBorders);
pictureForm.call("SetPicturePosition", shiftX, shiftY);
pictureForm.call("SetImage", imageUrl);
}
public static void setTextFormProperties(CDocBuilderValue textForm, String key, String tip, boolean required, String placeholder, boolean comb, int maxCharacters, int cellWidth, boolean multiLine, boolean autoFit) {
textForm.call("SetFormKey", key);
textForm.call("SetTipText", tip);
textForm.call("SetRequired", required);
textForm.call("SetPlaceholderText", placeholder);
textForm.call("SetComb", comb);
textForm.call("SetCharactersLimit", maxCharacters);
textForm.call("SetCellWidth", cellWidth);
textForm.call("SetCellWidth", multiLine);
textForm.call("SetMultiline", autoFit);
}
}

View File

@ -0,0 +1,123 @@
import docbuilder.*;
import java.util.HashMap;
public class Program {
public static void main(String[] args) {
String resultPath = "result.pptx";
// Fill slide images
HashMap<String, String> slideImages = new HashMap<String, String>();
slideImages.put("gun", "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_gun.png");
slideImages.put("axe", "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_axe.png");
slideImages.put("knight", "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_knight.png");
slideImages.put("sky", "https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_sky.png");
createPresentation(resultPath, slideImages);
// Need to explicitly call System.gc() to free up resources
System.gc();
}
public static void createPresentation(String resultPath, HashMap<String, String> slideImages) {
int doctype = FileTypes.Presentation.PPTX;
// Initialize builder with docbuilder.jar directory by passing empty String
CDocBuilder.initialize("");
CDocBuilder builder = new CDocBuilder();
builder.createFile(doctype);
CDocBuilderContext context = builder.getContext();
CDocBuilderValue global = context.getGlobal();
CDocBuilderValue api = global.get("Api");
// Create presentation
CDocBuilderValue presentation = api.call("GetPresentation");
presentation.call("SetSizes", 9144000, 6858000);
CDocBuilderValue slide = createImageSlide(api, presentation, slideImages.get("gun"));
presentation.call("GetSlideByIndex", 0).call("Delete");
CDocBuilderValue shape = api.call("CreateShape", "rect", 8056800, 3020400, api.call("CreateNoFill"), api.call("CreateStroke", 0, api.call("CreateNoFill")));
shape.call("SetPosition", 608400, 1267200);
CDocBuilderValue content = shape.call("GetDocContent");
content.call("RemoveAllElements");
addTextToSlideShape(api, content, "How They", 160, true, "left");
addTextToSlideShape(api, content, "Throw Out", 132, false, "left");
addTextToSlideShape(api, content, "a Challenge", 132, false, "left");
slide.call("AddObject", shape);
slide = createImageSlide(api, presentation, slideImages.get("axe"));
shape = api.call("CreateShape", "rect", 6904800, 1724400, api.call("CreateNoFill"), api.call("CreateStroke", 0, api.call("CreateNoFill")));
shape.call("SetPosition", 1764000, 1191600);
content = shape.call("GetDocContent");
content.call("RemoveAllElements");
addTextToSlideShape(api, content, "American Indians ", 110, true, "right");
addTextToSlideShape(api, content, "(XVII century)", 94, false, "right");
slide.call("AddObject", shape);
shape = api.call("CreateShape", "rect", 4986000, 2419200, api.call("CreateNoFill"), api.call("CreateStroke", 0, api.call("CreateNoFill")));
shape.call("SetPosition", 3834000, 3888000);
content = shape.call("GetDocContent");
content.call("RemoveAllElements");
addTextToSlideShape(api, content, "put a tomahawk on the ground in the ", 84, false, "right");
addTextToSlideShape(api, content, "rival's camp", 84, false, "right");
slide.call("AddObject", shape);
slide = createImageSlide(api, presentation, slideImages.get("knight"));
shape = api.call("CreateShape", "rect", 6904800, 1724400, api.call("CreateNoFill"), api.call("CreateStroke", 0, api.call("CreateNoFill")));
shape.call("SetPosition", 1764000, 1191600);
content = shape.call("GetDocContent");
content.call("RemoveAllElements");
addTextToSlideShape(api, content, "European Knights", 110, true, "right");
addTextToSlideShape(api, content, " (XII-XVI centuries)", 94, false, "right");
slide.call("AddObject", shape);
shape = api.call("CreateShape", "rect", 4986000, 2419200, api.call("CreateNoFill"), api.call("CreateStroke", 0, api.call("CreateNoFill")));
shape.call("SetPosition", 3834000, 3888000);
content = shape.call("GetDocContent");
content.call("RemoveAllElements");
addTextToSlideShape(api, content, "threw a glove", 84, false, "right");
addTextToSlideShape(api, content, "in the rival's face", 84, false, "right");
slide.call("AddObject", shape);
slide = createImageSlide(api, presentation, slideImages.get("sky"));
shape = api.call("CreateShape", "rect", 7887600, 3063600, api.call("CreateNoFill"), api.call("CreateStroke", 0, api.call("CreateNoFill")));
shape.call("SetPosition", 630000, 1357200);
content = shape.call("GetDocContent");
content.call("RemoveAllElements");
addTextToSlideShape(api, content, "OnlyOffice", 176, false, "center");
addTextToSlideShape(api, content, "stands for Peace", 132, false, "center");
slide.call("AddObject", shape);
// Save file and close DocBuilder
builder.saveFile(doctype, resultPath);
builder.closeFile();
CDocBuilder.dispose();
}
public static CDocBuilderValue createImageSlide(CDocBuilderValue api, CDocBuilderValue presentation, String imageUrl) {
CDocBuilderValue slide = api.call("CreateSlide");
presentation.call("AddSlide", slide);
CDocBuilderValue fill = api.call("CreateBlipFill", imageUrl, "stretch");
slide.call("SetBackground", fill);
slide.call("RemoveAllObjects");
return slide;
}
public static void addTextToSlideShape(CDocBuilderValue api, CDocBuilderValue content, String text, int fontSize, boolean isBold, String js) {
CDocBuilderValue paragraph = api.call("CreateParagraph");
paragraph.call("SetSpacingBefore", 0);
paragraph.call("SetSpacingAfter", 0);
content.call("Push", paragraph);
CDocBuilderValue run = paragraph.call("AddText", text);
run.call("SetFill", api.call("CreateSolidFill", api.call("CreateRGBColor", 0xff, 0xff, 0xff)));
run.call("SetFontSize", fontSize);
run.call("SetFontFamily", "Georgia");
run.call("SetBold", isBold);
paragraph.call("SetJc", js);
}
}

View File

@ -0,0 +1,54 @@
import docbuilder.*;
public class Program {
public static void main(String[] args) {
String resultPath = "result.xlsx";
// Fill table data
Object[][] data = {
{ "Id", "Product", "Price", "Available" },
{ 1001, "Item A", 12.2, true },
{ 1002, "Item B", 18.8, true },
{ 1003, "Item C", 70.1, false },
{ 1004, "Item D", 60.6, true },
{ 1005, "Item E", 32.6, true },
{ 1006, "Item F", 28.3, false },
{ 1007, "Item G", 11.1, false },
{ 1008, "Item H", 41.4, true }
};
fillSpreadsheet(resultPath, data);
// Need to explicitly call System.gc() to free up resources
System.gc();
}
public static void fillSpreadsheet(String resultPath, Object[][] data) {
int doctype = FileTypes.Spreadsheet.XLSX;
// Initialize builder with docbuilder.jar directory by passing empty String
CDocBuilder.initialize("");
CDocBuilder builder = new CDocBuilder();
builder.createFile(doctype);
CDocBuilderContext context = builder.getContext();
CDocBuilderValue global = context.getGlobal();
CDocBuilderValue api = global.get("Api");
// Create spreadsheet
CDocBuilderValue worksheet = api.call("GetActiveSheet");
// Convert data to array value type
CDocBuilderValue array = new CDocBuilderValue(data);
// First cell in the range (A1) is equal to (0,0)
CDocBuilderValue startCell = worksheet.call("GetRangeByNumber", 0, 0);
// Last cell in the range is equal to array length -1
CDocBuilderValue endCell = worksheet.call("GetRangeByNumber", array.getLength() - 1, array.get(0).getLength() - 1);
worksheet.call("GetRange", startCell, endCell).call("SetValue", array);
// Save file and close DocBuilder
builder.saveFile(doctype, resultPath);
builder.closeFile();
CDocBuilder.dispose();
}
}

View File

@ -0,0 +1,60 @@
import os
import sys
sys.path.append('C:/Program Files/ONLYOFFICE/DocumentBuilder')
import docbuilder
# Helper functions
def setPictureFormProperties(pictureForm, key, tip, required, placeholder, scaleFlag, lockAspectRatio, respectBorders, shiftX, shiftY, imageUrl):
pictureForm.Call('SetFormKey', key)
pictureForm.Call('SetTipText', tip)
pictureForm.Call('SetRequired', required)
pictureForm.Call('SetPlaceholderText', placeholder)
pictureForm.Call('SetScaleFlag', scaleFlag)
pictureForm.Call('SetLockAspectRatio', lockAspectRatio)
pictureForm.Call('SetRespectBorders', respectBorders)
pictureForm.Call('SetPicturePosition', shiftX, shiftY)
pictureForm.Call('SetImage', imageUrl)
def setTextFormProperties(textForm, key, tip, required, placeholder, comb, maxCharacters, cellWidth, multiLine, autoFit):
textForm.Call('SetFormKey', key)
textForm.Call('SetTipText', tip)
textForm.Call('SetRequired', required)
textForm.Call('SetPlaceholderText', placeholder)
textForm.Call('SetComb', comb)
textForm.Call('SetCharactersLimit', maxCharacters)
textForm.Call('SetCellWidth', cellWidth)
textForm.Call('SetCellWidth', multiLine)
textForm.Call('SetMultiline', autoFit)
if __name__ == '__main__':
builder = docbuilder.CDocBuilder()
builder.CreateFile(docbuilder.FileTypes.Document.DOCX)
context = builder.GetContext()
globalObj = context.GetGlobal()
api = globalObj['Api']
document = api.Call('GetDocument')
paragraph = document.Call('GetElement', 0)
headingStyle = document.Call('GetStyle', 'Heading 3')
paragraph.Call('AddText', 'Employee pass card')
paragraph.Call('SetStyle', headingStyle)
document.Call('Push', paragraph)
pictureForm = api.Call('CreatePictureForm')
setPictureFormProperties(pictureForm, 'Photo', 'Upload your photo', False, 'Photo', 'tooBig', True, False, 50, 50, 'https://api.onlyoffice.com/content/img/docbuilder/examples/user-profile.png')
paragraph = api.Call('CreateParagraph')
paragraph.Call('AddElement', pictureForm)
document.Call('Push', paragraph)
textForm = api.Call('CreateTextForm')
setTextFormProperties(textForm, 'First name', 'Enter your first name', False, 'First name', True, 13, 3, False, False)
paragraph = api.Call('CreateParagraph')
paragraph.Call('AddElement', textForm)
document.Call('Push', paragraph)
# Save and close
resultPath = os.getcwd() + '/result.docx'
builder.SaveFile(docbuilder.FileTypes.Document.DOCX, resultPath)
builder.CloseFile()

View File

@ -0,0 +1,105 @@
import os
import sys
sys.path.append('C:/Program Files/ONLYOFFICE/DocumentBuilder')
import docbuilder
def createImageSlide(api, presentation, image_url):
slide = api.Call('CreateSlide')
presentation.Call('AddSlide', slide)
fill = api.Call('CreateBlipFill', image_url, 'stretch')
slide.Call('SetBackground', fill)
slide.Call('RemoveAllObjects')
return slide
def addTextToSlideShape(api, content, text, fontSize, isBold, js):
paragraph = api.Call('CreateParagraph')
paragraph.Call('SetSpacingBefore', 0)
paragraph.Call('SetSpacingAfter', 0)
content.Call('Push', paragraph)
run = paragraph.Call('AddText', text)
run.Call('SetFill', api.Call('CreateSolidFill', api.Call('CreateRGBColor', 0xff, 0xff, 0xff)))
run.Call('SetFontSize', fontSize)
run.Call('SetFontFamily', 'Georgia')
run.Call('SetBold', isBold)
paragraph.Call('SetJc', js)
if __name__ == '__main__':
slideImages = {}
slideImages['gun'] = 'https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_gun.png'
slideImages['axe'] = 'https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_axe.png'
slideImages['knight'] = 'https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_knight.png'
slideImages['sky'] = 'https://api.onlyoffice.com/content/img/docbuilder/examples/presentation_sky.png'
builder = docbuilder.CDocBuilder()
builder.CreateFile(docbuilder.FileTypes.Presentation.PPTX)
context = builder.GetContext()
globalObj = context.GetGlobal()
api = globalObj['Api']
# Create presentation
presentation = api.Call('GetPresentation')
presentation.Call('SetSizes', 9144000, 6858000)
slide = createImageSlide(api, presentation, slideImages['gun'])
presentation.Call('GetSlideByIndex', 0).Call('Delete')
shape = api.Call('CreateShape', 'rect', 8056800, 3020400, api.Call('CreateNoFill'), api.Call('CreateStroke', 0, api.Call('CreateNoFill')))
shape.Call('SetPosition', 608400, 1267200)
content = shape.Call('GetDocContent')
content.Call('RemoveAllElements')
addTextToSlideShape(api, content, 'How They', 160, True, 'left')
addTextToSlideShape(api, content, 'Throw Out', 132, False, 'left')
addTextToSlideShape(api, content, 'a Challenge', 132, False, 'left')
slide.Call('AddObject', shape)
slide = createImageSlide(api, presentation, slideImages['axe'])
shape = api.Call('CreateShape', 'rect', 6904800, 1724400, api.Call('CreateNoFill'), api.Call('CreateStroke', 0, api.Call('CreateNoFill')))
shape.Call('SetPosition', 1764000, 1191600)
content = shape.Call('GetDocContent')
content.Call('RemoveAllElements')
addTextToSlideShape(api, content, 'American Indians ', 110, True, 'right')
addTextToSlideShape(api, content, '(XVII century)', 94, False, 'right')
slide.Call('AddObject', shape)
shape = api.Call('CreateShape', 'rect', 4986000, 2419200, api.Call('CreateNoFill'), api.Call('CreateStroke', 0, api.Call('CreateNoFill')))
shape.Call('SetPosition', 3834000, 3888000)
content = shape.Call('GetDocContent')
content.Call('RemoveAllElements')
addTextToSlideShape(api, content, 'put a tomahawk on the ground in the ', 84, False, 'right')
addTextToSlideShape(api, content, 'rival\'s camp', 84, False, 'right')
slide.Call('AddObject', shape)
slide = createImageSlide(api, presentation, slideImages['knight'])
shape = api.Call('CreateShape', 'rect', 6904800, 1724400, api.Call('CreateNoFill'), api.Call('CreateStroke', 0, api.Call('CreateNoFill')))
shape.Call('SetPosition', 1764000, 1191600)
content = shape.Call('GetDocContent')
content.Call('RemoveAllElements')
addTextToSlideShape(api, content, 'European Knights', 110, True, 'right')
addTextToSlideShape(api, content, ' (XII-XVI centuries)', 94, False, 'right')
slide.Call('AddObject', shape)
shape = api.Call('CreateShape', 'rect', 4986000, 2419200, api.Call('CreateNoFill'), api.Call('CreateStroke', 0, api.Call('CreateNoFill')))
shape.Call('SetPosition', 3834000, 3888000)
content = shape.Call('GetDocContent')
content.Call('RemoveAllElements')
addTextToSlideShape(api, content, 'threw a glove', 84, False, 'right')
addTextToSlideShape(api, content, 'in the rival\'s face', 84, False, 'right')
slide.Call('AddObject', shape)
slide = createImageSlide(api, presentation, slideImages['sky'])
shape = api.Call('CreateShape', 'rect', 7887600, 3063600, api.Call('CreateNoFill'), api.Call('CreateStroke', 0, api.Call('CreateNoFill')))
shape.Call('SetPosition', 630000, 1357200)
content = shape.Call('GetDocContent')
content.Call('RemoveAllElements')
addTextToSlideShape(api, content, 'OnlyOffice', 176, False, 'center')
addTextToSlideShape(api, content, 'stands for Peace', 132, False, 'center')
slide.Call('AddObject', shape)
# Save and close
resultPath = os.getcwd() + '/result.pptx'
builder.SaveFile(docbuilder.FileTypes.Presentation.PPTX, resultPath)
builder.CloseFile()

View File

@ -0,0 +1,42 @@
import os
import sys
sys.path.append('C:/Program Files/ONLYOFFICE/DocumentBuilder')
import docbuilder
if __name__ == '__main__':
data = [
[ 'Id', 'Product', 'Price', 'Available' ],
[ '1001', 'Item A', "12.2", 'true' ],
[ '1002', 'Item B', "18.8", 'true' ],
[ '1003', 'Item C', "70.1", 'false' ],
[ '1004', 'Item D', "60.6", 'true' ],
[ '1005', 'Item E', "32.6", 'true' ],
[ '1006', 'Item F', "28.3", 'false' ],
[ '1007', 'Item G', "11.1", 'false' ],
[ '1008', 'Item H', "41.4", 'true' ]
]
builder = docbuilder.CDocBuilder()
builder.CreateFile(docbuilder.FileTypes.Spreadsheet.XLSX)
context = builder.GetContext()
globalObj = context.GetGlobal()
api = globalObj['Api']
# Find and comment formula errors
worksheet = api.Call('GetActiveSheet')
# Create array from data
array = docbuilder.CDocBuilderValue(data)
# First cell in the range (A1) is equal to (0,0)
startCell = worksheet.Call('GetRangeByNumber', 0, 0)
# Last cell in the range is equal to array length -1
endCell = worksheet.Call('GetRangeByNumber', len(data) - 1, len(data[0]) - 1)
worksheet.Call('GetRange', startCell, endCell).Call('SetValue', array)
# Save and close
resultPath = os.getcwd() + '/result.xlsx'
builder.SaveFile(docbuilder.FileTypes.Spreadsheet.XLSX, resultPath)
builder.CloseFile()

View File

@ -0,0 +1,258 @@
/*
* (c) Copyright Ascensio System SIA 2010-2023
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-6 Ernesta Birznieka-Upish
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
// convenient macro definitions
#if defined(__linux__) || defined(__linux)
#define _LINUX
#elif defined(__APPLE__) || defined(__MACH__)
#define _MAC
#endif
#include <string>
#ifdef _WIN32
#include <wchar.h>
#include <windows.h>
#endif
#if defined(_LINUX) || defined(_MAC)
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#endif
#ifdef _MAC
#include <mach-o/dyld.h>
#endif
#ifdef CreateFile
#undef CreateFile
#endif
namespace NSUtils
{
#ifdef _WIN32
#define PATH_SEPARATOR '\\'
#define WriteCodepoint(code) \
if (code < 0x10000) \
*unicodes_cur++ = code; \
else \
{ \
code -= 0x10000; \
*unicodes_cur++ = 0xD800 | ((code >> 10) & 0x03FF); \
*unicodes_cur++ = 0xDC00 | (code & 0x03FF); \
}
#else
#define PATH_SEPARATOR '/'
#define WriteCodepoint(code) *unicodes_cur++ = (wchar_t)code;
#endif
std::wstring GetStringFromUtf8(const unsigned char* utf8, size_t length)
{
wchar_t* unicodes = new wchar_t[length + 1];
wchar_t* unicodes_cur = unicodes;
size_t index = 0;
while (index < length)
{
unsigned char byteMain = utf8[index];
if (0x00 == (byteMain & 0x80))
{
// 1 byte
WriteCodepoint(byteMain)
++index;
}
else if (0x00 == (byteMain & 0x20))
{
// 2 byte
int val = 0;
if ((index + 1) < length)
{
val = (int)(((byteMain & 0x1F) << 6) |
(utf8[index + 1] & 0x3F));
}
WriteCodepoint(val)
index += 2;
}
else if (0x00 == (byteMain & 0x10))
{
// 3 byte
int val = 0;
if ((index + 2) < length)
{
val = (int)(((byteMain & 0x0F) << 12) |
((utf8[index + 1] & 0x3F) << 6) |
(utf8[index + 2] & 0x3F));
}
WriteCodepoint(val)
index += 3;
}
else if (0x00 == (byteMain & 0x0F))
{
// 4 byte
int val = 0;
if ((index + 3) < length)
{
val = (int)(((byteMain & 0x07) << 18) |
((utf8[index + 1] & 0x3F) << 12) |
((utf8[index + 2] & 0x3F) << 6) |
(utf8[index + 3] & 0x3F));
}
WriteCodepoint(val)
index += 4;
}
else if (0x00 == (byteMain & 0x08))
{
// 4 byte
int val = 0;
if ((index + 3) < length)
{
val = (int)(((byteMain & 0x07) << 18) |
((utf8[index + 1] & 0x3F) << 12) |
((utf8[index + 2] & 0x3F) << 6) |
(utf8[index + 3] & 0x3F));
}
WriteCodepoint(val)
index += 4;
}
else if (0x00 == (byteMain & 0x04))
{
// 5 byte
int val = 0;
if ((index + 4) < length)
{
val = (int)(((byteMain & 0x03) << 24) |
((utf8[index + 1] & 0x3F) << 18) |
((utf8[index + 2] & 0x3F) << 12) |
((utf8[index + 3] & 0x3F) << 6) |
(utf8[index + 4] & 0x3F));
}
WriteCodepoint(val)
index += 5;
}
else
{
// 6 byte
int val = 0;
if ((index + 5) < length)
{
val = (int)(((byteMain & 0x01) << 30) |
((utf8[index + 1] & 0x3F) << 24) |
((utf8[index + 2] & 0x3F) << 18) |
((utf8[index + 3] & 0x3F) << 12) |
((utf8[index + 4] & 0x3F) << 6) |
(utf8[index + 5] & 0x3F));
}
WriteCodepoint(val)
index += 5;
}
}
*unicodes_cur++ = 0;
std::wstring sOutput(unicodes);
delete[] unicodes;
return sOutput;
}
}
namespace NSUtils
{
#define NS_FILE_MAX_PATH 32768
std::wstring GetProcessPath()
{
#ifdef _WIN32
wchar_t buf [NS_FILE_MAX_PATH];
GetModuleFileNameW(GetModuleHandle(NULL), buf, NS_FILE_MAX_PATH);
return std::wstring(buf);
#endif
#if defined(_LINUX) || defined(_MAC)
char buf[NS_FILE_MAX_PATH];
memset(buf, 0, NS_FILE_MAX_PATH);
if (readlink ("/proc/self/exe", buf, NS_FILE_MAX_PATH) <= 0)
{
#ifdef _MAC
uint32_t _size = NS_FILE_MAX_PATH;
_NSGetExecutablePath(buf, &_size);
#endif
}
return GetStringFromUtf8((unsigned char*)buf, strlen(buf));
#endif
}
std::wstring GetProcessDirectory()
{
std::wstring path = GetProcessPath();
size_t pos = path.find_last_of(PATH_SEPARATOR);
if (pos != std::wstring::npos)
path = path.substr(0, pos);
return path;
}
std::wstring GetResourcesDirectory()
{
std::wstring path = GetProcessDirectory();
while (!path.empty())
{
size_t pos = path.find_last_of(PATH_SEPARATOR);
if (pos != std::wstring::npos)
{
std::wstring currDir = path.substr(pos + 1);
if (currDir == L"samples")
{
path += PATH_SEPARATOR;
path += L"resources";
break;
}
else
{
path = path.substr(0, pos);
}
}
else
{
path = L"";
}
}
return path;
}
}

View File

@ -32,19 +32,11 @@
#ifndef SERVER_SETTINGS_H
#define SERVER_SETTINGS_H
#include <string>
#include <map>
#include "../common/File.h"
#include "../common/StringBuilder.h"
#include <iostream>
// class for server version (disable local files and etc)
class CServerInstance
{
private:
bool m_bIsEnabled;
std::map<std::wstring, bool> m_arMapTmpFiles;
CServerInstance()
{
m_bIsEnabled = false;
@ -66,32 +58,6 @@ public:
{
return m_bIsEnabled;
}
void AddTmpFile(const std::wstring& sFolder)
{
std::wstring sDirectory = sFolder + L"/media";
NSStringUtils::string_replace(sDirectory, L"\\", L"/");
std::map<std::wstring, bool>::iterator findDir = m_arMapTmpFiles.find(sDirectory);
if (findDir == m_arMapTmpFiles.end())
m_arMapTmpFiles.insert(std::make_pair(sDirectory, true));
}
void RemoveTmpFile(const std::wstring& sFolder)
{
std::wstring sDirectory = sFolder + L"/media";
NSStringUtils::string_replace(sDirectory, L"\\", L"/");
std::map<std::wstring, bool>::iterator findDir = m_arMapTmpFiles.find(sDirectory);
if (findDir != m_arMapTmpFiles.end())
m_arMapTmpFiles.erase(findDir);
}
bool CheckTmpDirectory(const std::wstring& sFile)
{
std::wstring sDirectory = NSFile::GetDirectoryName(sFile);
NSStringUtils::string_replace(sDirectory, L"\\", L"/");
std::map<std::wstring, bool>::iterator findDir = m_arMapTmpFiles.find(sDirectory);
return (findDir != m_arMapTmpFiles.end()) ? true : false;
}
};

View File

@ -467,62 +467,6 @@ TEST_F(CJSONTest, object)
EXPECT_FALSE(compare(obj, jsObj->toValue(), false));
}
TEST_F(CJSONTest, image_externalize)
{
int width = 1080;
int height = 480;
BYTE* bits = CValue::AllocImageBits(width, height);
CValue img = CValue::CreateImage(bits, width, height, ifBGRA);
EXPECT_TRUE(img.IsImage());
EXPECT_EQ(img.GetImageBits(), bits);
EXPECT_EQ(img.GetImageWidth(), width);
EXPECT_EQ(img.GetImageHeight(), height);
EXPECT_EQ(img.GetImageFormat(), ifBGRA);
CValue::FreeImageBits(bits);
width = 50;
height = 100;
bits = CValue::AllocImageBits(width, height);
img = CValue::CreateImage(bits, width, height, ifRGBA);
EXPECT_TRUE(img.IsImage());
EXPECT_EQ(img.GetImageBits(), bits);
EXPECT_EQ(img.GetImageWidth(), width);
EXPECT_EQ(img.GetImageHeight(), height);
EXPECT_EQ(img.GetImageFormat(), ifRGBA);
CValue::FreeImageBits(bits);
}
TEST_F(CJSONTest, image_not_externalize)
{
int width = 320;
int height = 480;
BYTE* bits = CValue::AllocImageBits(width, height);
CValue img = CValue::CreateImage(bits, width, height, ifARGB, false);
EXPECT_TRUE(img.IsImage());
EXPECT_EQ(img.GetImageBits(), bits);
EXPECT_EQ(img.GetImageWidth(), width);
EXPECT_EQ(img.GetImageHeight(), height);
EXPECT_EQ(img.GetImageFormat(), ifARGB);
}
TEST_F(CJSONTest, image_wrong_size)
{
BYTE* bits = CValue::AllocImageBits(100, 100);
CValue img = CValue::CreateImage(bits, 0, 100, ifARGB, false);
EXPECT_TRUE(img.IsUndefined());
img = CValue::CreateImage(bits, -1, 100, ifARGB, false);
EXPECT_TRUE(img.IsUndefined());
img = CValue::CreateImage(bits, 0, 0, ifARGB, false);
EXPECT_TRUE(img.IsUndefined());
img = CValue::CreateImage(bits, -100, -100, ifARGB, false);
EXPECT_TRUE(img.IsUndefined());
}
TEST_F(CJSONTest, references)
{
CValue val = 42;
@ -582,20 +526,12 @@ TEST_F(CJSONTest, wrong_usage)
EXPECT_THROW(val.GetPropertyNames(), std::bad_cast);
EXPECT_THROW(val.GetCount(), std::bad_cast);
EXPECT_THROW(val.GetData(), std::bad_cast);
EXPECT_THROW(val.GetImageBits(), std::bad_cast);
EXPECT_THROW(val.GetImageFormat(), std::bad_cast);
EXPECT_THROW(val.GetImageHeight(), std::bad_cast);
EXPECT_THROW(val.GetImageWidth(), std::bad_cast);
#else
EXPECT_TRUE(val["name"].IsUndefined());
EXPECT_TRUE(val[0].IsUndefined());
EXPECT_TRUE(val.GetPropertyNames().empty());
EXPECT_EQ(val.GetCount(), 0);
EXPECT_EQ(val.GetData(), nullptr);
EXPECT_EQ(val.GetImageBits(), nullptr);
EXPECT_EQ(val.GetImageFormat(), ifInvalid);
EXPECT_EQ(val.GetImageHeight(), 0);
EXPECT_EQ(val.GetImageWidth(), 0);
#endif
EXPECT_DOUBLE_EQ(val.ToDouble(), 42.0);
#ifdef JSON_DEBUG
@ -1665,11 +1601,7 @@ TEST_F(CJSONTest, FromJSON_arrays)
CValue val = CValue::FromJSON(strJson);
EXPECT_TRUE(val.IsArray());
EXPECT_EQ(val.GetCount(), 0);
#ifndef JSON_DEBUG
EXPECT_TRUE(val[0].IsUndefined());
#else
EXPECT_THROW(val[0], std::out_of_range);
#endif
strJson = "[1, 2, 3]";
val = CValue::FromJSON(strJson);

View File

@ -1,4 +1,5 @@
#include "AlphaMask_p.h"
#include "AlphaMask.h"
#include <string.h>
namespace Aggplus
{
@ -32,6 +33,7 @@ namespace Aggplus
{
case EMaskDataType::ImageBuffer: return 4;
case EMaskDataType::AlphaBuffer: return 1;
case EMaskDataType::Alpha4Buffer: return 4;
}
}
@ -63,26 +65,130 @@ namespace Aggplus
return Ok;
}
CSoftMask::CSoftMask(BYTE* pBuffer, unsigned int unWidth, unsigned int unHeight, bool bFlip, bool bRGB, bool bAlpha)
CSoftMask::CSoftMask() : m_unWidth(0), m_unHeight(0), m_pImageData(NULL), m_pAlphaBufferData(NULL) {}
CSoftMask::CSoftMask(BYTE* pBuffer, UINT unWidth, UINT unHeight, EMaskDataType enDataType, bool bExternalBuffer, bool bFlip) : m_pImageData(NULL), m_pAlphaBufferData(NULL)
{
if (bAlpha)
m_pInternal = new CSoftMaskAlpha(pBuffer, unWidth, unHeight, false, bFlip);
else
{
if (bRGB)
m_pInternal = new CSoftMaskBGRAgray(pBuffer, unWidth, unHeight, false, bFlip);
else
m_pInternal = new CSoftMaskRGBAgray(pBuffer, unWidth, unHeight, false, bFlip);
}
LoadFromBuffer(pBuffer, unWidth, unHeight, enDataType, bExternalBuffer, bFlip);
}
CSoftMask::~CSoftMask()
{
RELEASEOBJECT(m_pInternal);
BYTE* pBuffer = m_oRenderingBuffer.buf();
if (NULL != pBuffer)
{
if (!m_bExternalBuffer)
RELEASEARRAYOBJECTS(pBuffer);
m_oRenderingBuffer.attach(NULL, 0, 0, 0);
}
RELEASEOBJECT(m_pImageData);
RELEASEOBJECT(m_pAlphaBufferData);
}
unsigned int CSoftMask::GetStep() const { return m_pInternal->GetStep(); }
unsigned int CSoftMask::GetWidth() const { return m_pInternal->GetWidth(); }
unsigned int CSoftMask::GetHeight() const { return m_pInternal->GetHeight(); }
BYTE* CSoftMask::GetBuffer() { return m_pInternal->GetBuffer(); }
ESoftMaskType CSoftMask::GetDataType() { return m_pInternal->GetDataType(); }
EMaskDataType CSoftMask::GetDataType() const { return m_enDataType; }
unsigned int CSoftMask::GetStep() const
{
switch(m_enDataType)
{
case EMaskDataType::ImageBuffer: return 4;
case EMaskDataType::AlphaBuffer: return 1;
case EMaskDataType::Alpha4Buffer: return 4;
}
}
unsigned int CSoftMask::GetWidth() const { return m_unWidth; }
unsigned int CSoftMask::GetHeight() const { return m_unHeight; }
void CSoftMask::SetType(EMaskDataType enDataType)
{
m_enDataType = enDataType;
RELEASEOBJECT(m_pImageData);
RELEASEOBJECT(m_pAlphaBufferData);
switch (enDataType)
{
case EMaskDataType::ImageBuffer:
{
m_pImageData = new AMaskFromImage(m_oRenderingBuffer);
m_pImageData->m_oRendererBase.attach(m_pImageData->m_oPixfmt);
m_pImageData->m_oAlphaMask.attach(m_oRenderingBuffer);
break;
}
case EMaskDataType::Alpha4Buffer:
{
m_pAlphaBufferData = new AMaskFromABuffer(m_oRenderingBuffer);
m_pAlphaBufferData->m_oRendererBase.attach(m_pAlphaBufferData->m_oPixfmt);
m_pAlphaBufferData->m_oAlphaMask.attach(m_oRenderingBuffer);
break;
}
}
}
Status CSoftMask::Create(UINT unWidth, UINT unHeight, EMaskDataType enDataType)
{
if (0 == unWidth || 0 == unHeight)
return InvalidParameter;
m_bExternalBuffer = false;
UINT unSize = unWidth * unHeight * GetStep();
BYTE* pAlphaBufffer = new BYTE[unSize];
if (!pAlphaBufffer)
return OutOfMemory;
memset(pAlphaBufffer, 0x00, unSize);
Set(pAlphaBufffer, unWidth, unHeight, enDataType);
return Ok;
}
Status CSoftMask::LoadFromBuffer(BYTE *pBuffer, UINT unWidth, UINT unHeight, EMaskDataType enDataType, bool bExternalBuffer, bool bFlip)
{
if (NULL == pBuffer || 0 == unWidth || 0 == unHeight)
return InvalidParameter;
m_bExternalBuffer = bExternalBuffer;
Set(pBuffer, unWidth, unHeight, enDataType, bFlip);
return Ok;
}
RenBaseBGRA32& CSoftMask::GetRendererBaseImage()
{
return m_pImageData->m_oRendererBase;
}
ScanlineBGRA32Gray& CSoftMask::GetScanlineImage()
{
return m_pImageData->m_oScanLine;
}
ScanlineBGRA32A& CSoftMask::GetScanlineABuffer()
{
return m_pAlphaBufferData->m_oScanLine;
}
BYTE* CSoftMask::GetBuffer()
{
return m_oRenderingBuffer.buf();
}
agg::rendering_buffer& CSoftMask::GetRenderingBuffer()
{
return m_oRenderingBuffer;
}
void CSoftMask::Set(BYTE* pBuffer, UINT unWidth, UINT unHeight, EMaskDataType enDataType, bool bFlip)
{
m_enDataType = enDataType;
m_unWidth = unWidth;
m_unHeight = unHeight;
m_oRenderingBuffer.attach(pBuffer, unWidth, unHeight, (bFlip ? -1 : 1) * GetStep() * unWidth);
SetType(enDataType);
}
}

View File

@ -1,16 +1,23 @@
#ifndef _BUILD_ALPHAMASK_H_
#define _BUILD_ALPHAMASK_H_
#include <string>
#include "aggplustypes.h"
#include "../common/IGrObject.h"
#include "./config.h"
#include "../agg-2.4/include/agg_renderer_base.h"
#include "../agg-2.4/include/agg_pixfmt_rgba.h"
#include "../agg-2.4/include/agg_scanline_u.h"
#include "../agg-2.4/include/agg_alpha_mask_u8.h"
namespace Aggplus
{
enum class EMaskDataType
{
ImageBuffer,
AlphaBuffer
AlphaBuffer,
Alpha4Buffer
};
class GRAPHICS_DECL CAlphaMask : public IGrObject
@ -32,30 +39,56 @@ namespace Aggplus
bool m_bExternalBuffer;
};
enum class ESoftMaskType
template <class PixelFormat, class AlphaMask>
struct TAlphaMaskData
{
RGBGrayBuffer,
BGRGrayBuffer,
Alpha4Buffer
TAlphaMaskData(agg::rendering_buffer& oRenderingBuffer) : m_oPixfmt(oRenderingBuffer), m_oScanLine(m_oAlphaMask) {};
PixelFormat m_oPixfmt;
agg::renderer_base<PixelFormat> m_oRendererBase;
AlphaMask m_oAlphaMask;
agg::scanline_u8_am<AlphaMask> m_oScanLine;
};
class CSoftMask_private;
typedef agg::renderer_base<agg::pixfmt_bgra32> RenBaseBGRA32;
typedef agg::scanline_u8_am<agg::alpha_mask_bgra32gray> ScanlineBGRA32Gray;
typedef agg::scanline_u8_am<agg::alpha_mask_bgra32a> ScanlineBGRA32A;
class GRAPHICS_DECL CSoftMask : public IGrObject
{
public:
CSoftMask(BYTE* pBuffer, unsigned int unWidth, unsigned int unHeight, bool bFlip, bool bRGB, bool bAlpha);
~CSoftMask();
CSoftMask();
CSoftMask(BYTE* pBuffer, UINT unWidth, UINT unHeight, EMaskDataType enDataType, bool bExternalBuffer = true, bool bFlip = false);
virtual ~CSoftMask();
EMaskDataType GetDataType() const;
unsigned int GetStep() const;
unsigned int GetWidth() const;
unsigned int GetHeight() const;
BYTE* GetBuffer();
ESoftMaskType GetDataType();
void SetType(EMaskDataType enDataType);
Status Create(UINT unWidth, UINT unHeight, EMaskDataType enDataType);
Status LoadFromBuffer(BYTE* pBuffer, UINT unWidth, UINT unHeight, EMaskDataType enDataType, bool bExternalBuffer = true, bool bFlip = false);
agg::rendering_buffer& GetRenderingBuffer();
RenBaseBGRA32& GetRendererBaseImage();
ScanlineBGRA32Gray& GetScanlineImage();
ScanlineBGRA32A& GetScanlineABuffer();
BYTE* GetBuffer();
private:
CSoftMask_private* m_pInternal;
void Set(BYTE* pBuffer, UINT unWidth, UINT unHeight, EMaskDataType enDataType, bool bFlip = false);
friend class CGraphics;
agg::rendering_buffer m_oRenderingBuffer;
EMaskDataType m_enDataType;
bool m_bExternalBuffer;
unsigned int m_unWidth;
unsigned int m_unHeight;
typedef TAlphaMaskData<agg::pixfmt_bgra32, agg::alpha_mask_bgra32gray> AMaskFromImage;
typedef TAlphaMaskData<agg::pixfmt_bgra32, agg::alpha_mask_bgra32a> AMaskFromABuffer;
AMaskFromImage* m_pImageData;
AMaskFromABuffer* m_pAlphaBufferData;
};
}

View File

@ -1,96 +0,0 @@
#ifndef _BUILD_ALPHAMASK_P_H_
#define _BUILD_ALPHAMASK_P_H_
#include "AlphaMask.h"
#include <string>
#include <string.h>
#include "../agg-2.4/include/agg_rendering_buffer.h"
#include "../agg-2.4/include/agg_scanline_u.h"
#include "../agg-2.4/include/agg_alpha_mask_u8.h"
namespace Aggplus
{
class CSoftMask_private
{
public:
virtual ~CSoftMask_private()
{
BYTE* pBuffer = m_oRenderingBuffer.buf();
if (NULL != pBuffer)
{
if (!m_bExternalBuffer)
RELEASEARRAYOBJECTS(pBuffer);
m_oRenderingBuffer.attach(NULL, 0, 0, 0);
}
}
unsigned int GetStep() const { return 4; }
unsigned int GetWidth() const { return m_unWidth; }
unsigned int GetHeight() const { return m_unHeight; }
BYTE* GetBuffer() { return m_oRenderingBuffer.buf(); }
virtual ESoftMaskType GetDataType() const = 0;
virtual bool GetSwapRGB() const { return true; };
protected:
CSoftMask_private(BYTE* pBuffer, unsigned int unWidth, unsigned int unHeight, bool bExternalBuffer, bool bFlip)
{
m_bExternalBuffer = bExternalBuffer;
m_unWidth = unWidth;
m_unHeight = unHeight;
m_oRenderingBuffer.attach(pBuffer, unWidth, unHeight, (bFlip ? -1 : 1) * GetStep() * unWidth);
}
agg::rendering_buffer m_oRenderingBuffer;
bool m_bExternalBuffer;
unsigned int m_unWidth;
unsigned int m_unHeight;
};
class CSoftMaskBGRAgray : public CSoftMask_private
{
public:
CSoftMaskBGRAgray(BYTE* pBuffer, unsigned int unWidth, unsigned int unHeight, bool bExternalBuffer, bool bFlip)
: CSoftMask_private(pBuffer, unWidth, unHeight, bExternalBuffer, bFlip), m_oAlphaMask(m_oRenderingBuffer), m_oScanLine(m_oAlphaMask) {}
agg::scanline_u8_am<agg::alpha_mask_bgra32gray>& GetScanline() { return m_oScanLine; }
virtual ESoftMaskType GetDataType() const override { return ESoftMaskType::BGRGrayBuffer; }
private:
agg::alpha_mask_bgra32gray m_oAlphaMask;
agg::scanline_u8_am<agg::alpha_mask_bgra32gray> m_oScanLine;
};
class CSoftMaskRGBAgray : public CSoftMask_private
{
public:
CSoftMaskRGBAgray(BYTE* pBuffer, unsigned int unWidth, unsigned int unHeight, bool bExternalBuffer, bool bFlip)
: CSoftMask_private(pBuffer, unWidth, unHeight, bExternalBuffer, bFlip), m_oAlphaMask(m_oRenderingBuffer), m_oScanLine(m_oAlphaMask) {}
agg::scanline_u8_am<agg::alpha_mask_rgba32gray>& GetScanline() { return m_oScanLine; }
virtual bool GetSwapRGB() const override { return false; };
virtual ESoftMaskType GetDataType() const override { return ESoftMaskType::RGBGrayBuffer; }
private:
agg::alpha_mask_rgba32gray m_oAlphaMask;
agg::scanline_u8_am<agg::alpha_mask_rgba32gray> m_oScanLine;
};
class CSoftMaskAlpha : public CSoftMask_private
{
public:
CSoftMaskAlpha(BYTE* pBuffer, unsigned int unWidth, unsigned int unHeight, bool bExternalBuffer, bool bFlip)
: CSoftMask_private(pBuffer, unWidth, unHeight, bExternalBuffer, bFlip), m_oAlphaMask(m_oRenderingBuffer), m_oScanLine(m_oAlphaMask) {}
agg::scanline_u8_am<agg::alpha_mask_rgba32a>& GetScanline() { return m_oScanLine; }
virtual ESoftMaskType GetDataType() const override { return ESoftMaskType::Alpha4Buffer; }
private:
agg::alpha_mask_rgba32a m_oAlphaMask;
agg::scanline_u8_am<agg::alpha_mask_rgba32a> m_oScanLine;
};
}
#endif // _BUILD_ALPHAMASK_P_H_

View File

@ -107,14 +107,9 @@ namespace NSThreads
{
if (i->ID == nThreadId)
{
CBaseThreadInfo last;
last.ID = i->ID;
last.Instance = i->Instance;
m_listThreads.erase(i);
m_listThreads.insert(m_listThreads.begin(), last);
return last.Instance;
m_listThreads.insert(m_listThreads.begin(), *i);
return i->Instance;
}
i++;
}

View File

@ -232,7 +232,6 @@ double Curve::GetTimeOf(const PointD& point) const noexcept
if (getDistance(point, GetPoint(u)) <= GEOMETRIC_EPSILON)
return u;
}
roots.clear();
}
}
bool firstDist = d0 <= GEOMETRIC_EPSILON,
@ -313,8 +312,8 @@ PointD Curve::Get(const double& t, const int& type) const noexcept
}
else if (t > tMax)
{
x0 = 3 * (x[3] - x[2]);
y0 = 3 * (y[3] - y[2]);
x0 = 3 * (x[3] - y[2]);
y0 = 3 * (y[3] - x[2]);
}
else
{
@ -370,7 +369,7 @@ Curve Curve::GetPart(double from, double to) const noexcept
result.Segment2.HO.X -= result.Segment2.P.X;
result.Segment2.HO.Y -= result.Segment2.P.Y;
}
if (to < 1)
else if (to < 1)
{
result = result.Subdivide((to - from) / (1 - from))[0];
result.Segment2.HI.X -= result.Segment2.P.X;
@ -654,11 +653,8 @@ int Curve::SolveCubic(double a, double b, double c, double d,
void Curve::Flip() noexcept
{
PointD tmpHI = Segment2.P + Segment2.HI;
PointD tmpHO = Segment2.P + Segment2.HO;
std::swap(Segment1.P, Segment2.P);
Segment2.HI = tmpHI - Segment2.P;
Segment2.HO = tmpHO - Segment2.P;
std::swap(Segment1.HI, Segment1.HO);
}
bool Curve::IsStraight() const noexcept
@ -711,14 +707,12 @@ bool Location::IsTouching() noexcept
CBooleanOperations::CBooleanOperations(const CGraphicsPath& path1,
const CGraphicsPath& path2,
BooleanOpType op,
long fillType) :
BooleanOpType op) :
Op(op),
Close1(path1.Is_poly_closed()),
Close2(path2.Is_poly_closed()),
Path1(path1),
Path2(path2),
FillType(fillType)
Path2(path2)
{
TraceBoolean();
}
@ -996,7 +990,7 @@ void CBooleanOperations::TracePaths()
start = true;
while (valid)
{
if (!start || (Op == Intersection && s.Inters && !GetNextSegment(s).Inters))
if (!start || (Op == Intersection && s.Inters))
SetVisited(s);
if (start)
@ -1048,12 +1042,12 @@ void CBooleanOperations::PreparePath(const CGraphicsPath& path, int id,
bool reverse)
{
bool isPolyClosed = path.Is_poly_closed();
int length = path.GetPointCount();
int length = isPolyClosed ? (path.GetPointCount() - 1) : path.GetPointCount();
int idx = 0;
if (reverse)
{
bool isCurve = false;
for (int i = length - 1; i >= 0; i--)
for (int i = length; i > 0; i--)
{
std::vector<PointD> points = path.GetPoints(isCurve ? i - 2 : i, isCurve ? 3 : 1);
if (isCurve) std::reverse(points.begin(), points.end());
@ -1093,10 +1087,10 @@ void CBooleanOperations::PreparePath(const CGraphicsPath& path, int id,
}
}
length = isPolyClosed ? static_cast<int>(segments.size()) : static_cast<int>(segments.size()) - 1;
length = segments.size();
for (int i = 0; i < length; i++)
curves.push_back(Curve(segments[i], isPolyClosed && (i == (length - 1)) ? segments[0] : segments[i + 1]));
curves.push_back(Curve(segments[i], i == (length - 1) ? segments[0] : segments[i + 1]));
}
void CBooleanOperations::InsertSegment(Segment& segment, const Segment& handles, bool updateHandles)
@ -1525,7 +1519,7 @@ void CBooleanOperations::AddCurveLineIntersection(const Curve& curve1, const Cur
}
}
int CBooleanOperations::AddCurveIntersection(const Curve& curve1, const Curve& curve2, const Curve& startCurve1,
int CBooleanOperations::AddCurveIntersection(Curve curve1, Curve curve2, const Curve& startCurve1,
const Curve& startCurve2, bool flip,
int recursion, int calls, double tMin,
double tMax, double uMin, double uMax)
@ -1548,9 +1542,9 @@ int CBooleanOperations::AddCurveIntersection(const Curve& curve1, const Curve& c
dp2 = getSignedDistance(x2[0], y2[0], x2[3], y2[3], x1[2], y1[2]),
dp3 = getSignedDistance(x2[0], y2[0], x2[3], y2[3], x1[3], y1[3]);
std::vector<PointD> top;
std::vector<PointD> bottom;
getConvexHull(dp0, dp1, dp2, dp3, top, bottom);
std::vector<std::vector<PointD>> hull = getConvexHull(dp0, dp1, dp2, dp3);
std::vector<PointD> top = hull[0],
bottom = hull[1];
double tMinClip = clipConvexHull(top, bottom, dMin, dMax);
@ -1581,14 +1575,14 @@ int CBooleanOperations::AddCurveIntersection(const Curve& curve1, const Curve& c
}
else
{
Curve newCurve1 = curve1.GetPart(tMinClip, tMaxClip);
curve1 = curve1.GetPart(tMinClip, tMaxClip);
double uDiff = uMax - uMin;
if (tMaxClip - tMinClip > 0.8)
{
if (tMaxNew - tMinNew > uDiff)
{
std::vector<Curve> parts = newCurve1.Subdivide(0.5);
std::vector<Curve> parts = curve1.Subdivide(0.5);
double t = (tMinNew + tMaxNew) / 2;
parts[0].Segment2.SetHandles(parts[0].Segment2.HI, parts[0].Segment2.HO);
@ -1607,19 +1601,19 @@ int CBooleanOperations::AddCurveIntersection(const Curve& curve1, const Curve& c
parts[0].Segment2.SetHandles(parts[0].Segment2.HI, parts[0].Segment2.HO);
parts[1].Segment2.SetHandles(parts[1].Segment2.HI, parts[1].Segment2.HO);
calls = AddCurveIntersection(parts[0], newCurve1, startCurve2, startCurve1,
calls = AddCurveIntersection(parts[0], curve1, startCurve2, startCurve1,
!flip, recursion, calls, uMin, u, tMinNew, tMaxNew);
calls = AddCurveIntersection(parts[1], newCurve1, startCurve2, startCurve1,
calls = AddCurveIntersection(parts[1], curve1, startCurve2, startCurve1,
!flip, recursion, calls, u, uMax, tMinNew, tMaxNew);
}
}
else
{
if (uDiff == 0 || uDiff >= LINE_EPSILON)
calls = AddCurveIntersection(curve2, newCurve1, startCurve2, startCurve1,
calls = AddCurveIntersection(curve2, curve1, startCurve2, startCurve1,
!flip, recursion, calls, uMin, uMax, tMinNew, tMaxNew);
else
calls = AddCurveIntersection(newCurve1, curve2, startCurve1, startCurve2,
calls = AddCurveIntersection(curve1, curve2, startCurve1, startCurve2,
flip, recursion, calls, tMinNew, tMaxNew, uMin, uMax);
}
}
@ -1632,12 +1626,14 @@ int CBooleanOperations::CheckInters(const PointD& point, const Segment& segment,
PointD pt{};
if (intersect({point.X, point.Y, segment.P.X, segment.P.Y, curve.Segment1.P.X, curve.Segment1.P.Y, curve.Segment2.P.X, curve.Segment2.P.Y}, pt))
{
if (getDistance(segment.P, pt) <= GEOMETRIC_EPSILON) return (touchCount + 1) % 2;
if (getDistance(curve.Segment1.P, pt) <= GEOMETRIC_EPSILON || getDistance(curve.Segment2.P, pt) <= GEOMETRIC_EPSILON)
return ++touchCount % 2;
{
int tmp = touchCount % 2;
touchCount++;
return tmp;
}
else if (curve.IsStraight())
{
touchCount++;
return 1;
}
}
@ -1711,10 +1707,6 @@ void CBooleanOperations::SetWinding()
} while (!s.IsEmpty() && !s.Inters && s != start);
}
}
if (FillType & c_nStroke)
for (auto& s : Segments2)
s.Winding = 0;
}
void CBooleanOperations::DivideLocations()
@ -1906,8 +1898,7 @@ void CBooleanOperations::AddOffsets(std::vector<double>& offsets,
CGraphicsPath CalcBooleanOperation(const CGraphicsPath& path1,
const CGraphicsPath& path2,
BooleanOpType op,
long fillType)
BooleanOpType op)
{
std::vector<CGraphicsPath> paths1 = path1.GetSubPaths(),
paths2 = path2.GetSubPaths(),
@ -1917,7 +1908,7 @@ CGraphicsPath CalcBooleanOperation(const CGraphicsPath& path1,
{
for (const auto& p2 : paths2)
{
CBooleanOperations operation(p1, p2, op, fillType);
CBooleanOperations operation(p1, p2, op);
paths.push_back(operation.GetResult());
}
}

View File

@ -107,7 +107,7 @@ namespace Aggplus
class CBooleanOperations
{
public:
CBooleanOperations(const CGraphicsPath& path1, const CGraphicsPath& path2, BooleanOpType op, long fillType = c_nWindingFillMode);
CBooleanOperations(const CGraphicsPath& path1, const CGraphicsPath& path2, BooleanOpType op);
~CBooleanOperations();
CGraphicsPath&& GetResult();
@ -140,7 +140,7 @@ namespace Aggplus
void LinkIntersection(std::shared_ptr<Location> form, std::shared_ptr<Location> to);
void AddLineIntersection(const Curve& curve1, const Curve& curve2);
void AddCurveLineIntersection(const Curve& curve1, const Curve& curve2, bool flip);
int AddCurveIntersection(const Curve& curve1, const Curve& curve2, const Curve& startCurve1, const Curve& startCurve2, bool flip,
int AddCurveIntersection(Curve curve1, Curve curve2, const Curve& startCurve1, const Curve& startCurve2, bool flip,
int recursion = 0, int calls = 0, double tMin = 0.0, double tMax = 1.0, double uMin = 0.0, double uMax = 1.0);
int CheckInters(const PointD& point, const Segment& segment, const Curve& curve, int& touchCount) const;
void SetWinding();
@ -159,9 +159,6 @@ namespace Aggplus
bool Close1 = true;
bool Close2 = true;
// c_nStroke, c_nWindingFillMode, c_nEvenOddFillMode
long FillType = c_nWindingFillMode;
CGraphicsPath Path1;
CGraphicsPath Path2;
CGraphicsPath Result;

View File

@ -1297,9 +1297,7 @@ namespace Aggplus
RELEASEINTERFACE(pCurrentGraphicsLayer);
RELEASEINTERFACE(m_pSoftMask);
unsigned int unWidth = m_frame_buffer.ren_buf().width(), unHeight = m_frame_buffer.ren_buf().height();
bool bFlip = m_frame_buffer.ren_buf().stride() < 0;
m_pSoftMask = new CSoftMask(pBuffer, unWidth, unHeight, bFlip, m_bSwapRGB, bAlpha);
m_pSoftMask = new CSoftMask(pBuffer, m_frame_buffer.ren_buf().width(), m_frame_buffer.ren_buf().height(), bAlpha ? EMaskDataType::Alpha4Buffer : EMaskDataType::ImageBuffer, false, m_frame_buffer.ren_buf().stride() < 0);
pBuffer = m_arLayers.empty() ? m_pPixels : m_arLayers.top()->GetBuffer();
if (!pBuffer)
@ -1308,7 +1306,7 @@ namespace Aggplus
return NULL;
}
m_frame_buffer.ren_buf().attach(pBuffer, unWidth, unHeight, m_frame_buffer.ren_buf().stride());
m_frame_buffer.ren_buf().attach(pBuffer, m_frame_buffer.ren_buf().width(), m_frame_buffer.ren_buf().height(), m_frame_buffer.ren_buf().stride());
return m_pSoftMask;
}
@ -1403,13 +1401,19 @@ namespace Aggplus
}
else if (m_pSoftMask)
{
ESoftMaskType nType = m_pSoftMask->GetDataType();
if (nType == ESoftMaskType::RGBGrayBuffer)
Aggplus::BlendTo<agg::rgb_to_gray_mask_u8<0, 1, 2>>(pCurrentGraphicsLayer, m_frame_buffer.pixfmt(), m_pSoftMask->GetBuffer(), m_pSoftMask->GetStep());
else if (nType == ESoftMaskType::BGRGrayBuffer)
switch(m_pSoftMask->GetDataType())
{
case EMaskDataType::ImageBuffer:
{
Aggplus::BlendTo<agg::rgb_to_gray_mask_u8<2, 1, 0>>(pCurrentGraphicsLayer, m_frame_buffer.pixfmt(), m_pSoftMask->GetBuffer(), m_pSoftMask->GetStep());
else if (nType == ESoftMaskType::Alpha4Buffer)
break;
}
case EMaskDataType::Alpha4Buffer:
{
Aggplus::BlendTo<agg::one_component_mask_u8>(pCurrentGraphicsLayer, m_frame_buffer.pixfmt(), m_pSoftMask->GetBuffer() + 3, m_pSoftMask->GetStep());
break;
}
}
}
else
{
@ -1545,13 +1549,10 @@ namespace Aggplus
{
if (m_pSoftMask)
{
ESoftMaskType nType = m_pSoftMask->GetDataType();
if (nType == ESoftMaskType::RGBGrayBuffer)
return render_scanlines_3(ras, ren, ((CSoftMaskRGBAgray*)m_pSoftMask->m_pInternal)->GetScanline());
if (nType == ESoftMaskType::BGRGrayBuffer)
return render_scanlines_3(ras, ren, ((CSoftMaskBGRAgray*)m_pSoftMask->m_pInternal)->GetScanline());
if (nType == ESoftMaskType::Alpha4Buffer)
return render_scanlines_3(ras, ren, ((CSoftMaskAlpha*)m_pSoftMask->m_pInternal)->GetScanline());
if (m_pSoftMask->GetDataType() == EMaskDataType::ImageBuffer)
return render_scanlines_3(ras, ren, m_pSoftMask->GetScanlineImage());
if (m_pSoftMask->GetDataType() == EMaskDataType::Alpha4Buffer)
return render_scanlines_3(ras, ren, m_pSoftMask->GetScanlineABuffer());
}
render_scanlines_3(ras, ren, m_rasterizer.get_scanline());
}

View File

@ -66,7 +66,7 @@
#include "Matrix.h"
#include "GraphicsLayerBlend.h"
#include "GraphicsPath.h"
#include "AlphaMask_p.h"
#include "AlphaMask.h"
#include "Clip.h"
#include "Brush.h"
#include "Image.h"

View File

@ -189,7 +189,7 @@ namespace Aggplus
Exclusion = 3
};
GRAPHICS_DECL CGraphicsPath CalcBooleanOperation(const CGraphicsPath& path1, const CGraphicsPath& path2, BooleanOpType op, long fillType = c_nWindingFillMode);
GRAPHICS_DECL CGraphicsPath CalcBooleanOperation(const CGraphicsPath& path1, const CGraphicsPath& path2, BooleanOpType op);
} // namespace Aggplus

View File

@ -955,62 +955,61 @@ HRESULT CGraphicsRenderer::DrawPath(const LONG& nType)
}
Aggplus::CBrushTexture* pTextureBrush = NULL;
if (NULL != m_oBrush.Image)
if (NULL != m_pCache)
{
pTextureBrush = new Aggplus::CBrushTexture(m_oBrush.Image, oMode);
}
else if (m_oBrush.TexturePath.find(L"data:") == 0)
{
bool bIsOnlyOfficeHatch = false;
if (m_oBrush.TexturePath.find(L"onlyoffice_hatch") != std::wstring::npos)
bIsOnlyOfficeHatch = true;
pCacheImage = (CCacheImage*)m_pCache->Lock(m_oBrush.TexturePath);
int countErase = (int)(m_oBrush.TexturePath.find(',') + 1);
int nInputSize = (int)(m_oBrush.TexturePath.length() - countErase);
const wchar_t* pInputSrc = m_oBrush.TexturePath.c_str() + countErase;
int nDecodeLen = NSBase64::Base64DecodeGetRequiredLength(nInputSize);
BYTE* pImageData = new BYTE[nDecodeLen];
if (TRUE == NSBase64::Base64Decode(pInputSrc, nInputSize, pImageData, &nDecodeLen))
{
CBgraFrame oFrame;
if (bIsOnlyOfficeHatch)
{
int nSize = (int)sqrt(nDecodeLen >> 2);
oFrame.put_IsRGBA(true);
oFrame.put_Data(pImageData);
oFrame.put_Width(nSize);
oFrame.put_Height(nSize);
oFrame.put_Stride(4 * nSize);
}
else
{
oFrame.put_IsRGBA(false);
oFrame.Decode(pImageData, nDecodeLen);
RELEASEARRAYOBJECTS(pImageData);
}
// pImage отдается pTextureBrush и освобождается вместе с pBrush
Aggplus::CImage* pImage = new Aggplus::CImage();
pImage->Create(oFrame.get_Data(), oFrame.get_Width(), oFrame.get_Height(), oFrame.get_Stride());
oFrame.ClearNoAttack();
pTextureBrush = new Aggplus::CBrushTexture(pImage, oMode);
pTextureBrush->m_bReleaseImage = TRUE;
}
else
RELEASEARRAYOBJECTS(pImageData);
pTextureBrush = new Aggplus::CBrushTexture(pCacheImage->GetImage(), oMode);
}
else
{
if (NULL != m_pCache)
#ifdef BUILDING_WASM_MODULE
if (NULL != m_oBrush.Image)
pTextureBrush = new Aggplus::CBrushTexture(m_oBrush.Image, oMode);
else if (m_oBrush.TexturePath.find(L"data:") == 0)
{
pCacheImage = (CCacheImage*)m_pCache->Lock(m_oBrush.TexturePath);
pTextureBrush = new Aggplus::CBrushTexture(pCacheImage->GetImage(), oMode);
bool bIsOnlyOfficeHatch = false;
if (m_oBrush.TexturePath.find(L"onlyoffice_hatch") != std::wstring::npos)
bIsOnlyOfficeHatch = true;
std::string sBase64MultyByte(m_oBrush.TexturePath.begin(), m_oBrush.TexturePath.end());
sBase64MultyByte.erase(0, sBase64MultyByte.find(',') + 1);
int nDecodeLen = NSBase64::Base64DecodeGetRequiredLength(sBase64MultyByte.length());
BYTE* pImageData = new BYTE[nDecodeLen + 64];
if (TRUE == NSBase64::Base64Decode(sBase64MultyByte.c_str(), sBase64MultyByte.length(), pImageData, &nDecodeLen))
{
CBgraFrame oFrame;
if (bIsOnlyOfficeHatch)
{
int nSize = (int)sqrt(nDecodeLen >> 2);
oFrame.put_IsRGBA(true);
oFrame.put_Data(pImageData);
oFrame.put_Width(nSize);
oFrame.put_Height(nSize);
oFrame.put_Stride(4 * nSize);
}
else
{
oFrame.put_IsRGBA(false);
oFrame.Decode(pImageData, nDecodeLen);
RELEASEARRAYOBJECTS(pImageData);
}
// pImage отдается pTextureBrush и освобождается вместе с pBrush
Aggplus::CImage* pImage = new Aggplus::CImage();
pImage->Create(oFrame.get_Data(), oFrame.get_Width(), oFrame.get_Height(), oFrame.get_Stride());
oFrame.ClearNoAttack();
pTextureBrush = new Aggplus::CBrushTexture(pImage, oMode);
pTextureBrush->m_bReleaseImage = TRUE;
}
else
RELEASEARRAYOBJECTS(pImageData);
}
#else
if (NULL != m_oBrush.Image)
pTextureBrush = new Aggplus::CBrushTexture(m_oBrush.Image, oMode);
else
{
pTextureBrush = new Aggplus::CBrushTexture(m_oBrush.TexturePath, oMode);
}
#endif
}
if( pTextureBrush )

View File

@ -229,10 +229,8 @@ bool intersect(std::vector<double> v, Aggplus::PointD& res)
return false;
}
void getConvexHull(const double& dq0, const double& dq1,
const double& dq2, const double& dq3,
std::vector<Aggplus::PointD>& top,
std::vector<Aggplus::PointD>& bottom)
std::vector<std::vector<Aggplus::PointD>> getConvexHull(const double& dq0, const double& dq1,
const double& dq2, const double& dq3)
{
Aggplus::PointD p0 = Aggplus::PointD(0.0, dq0),
p1 = Aggplus::PointD(1.0 / 3.0, dq1),
@ -242,59 +240,27 @@ void getConvexHull(const double& dq0, const double& dq1,
double dist1 = dq1 - (2.0 * dq0 + dq3) / 3.0,
dist2 = dq2 - (dq0 + 2.0 * dq3) / 3.0;
std::vector<std::vector<Aggplus::PointD>> hull;
if (dist1 * dist2 < 0.0)
{
top.reserve(3);
top.push_back(p0);
top.push_back(p1);
top.push_back(p3);
bottom.reserve(3);
bottom.push_back(p0);
bottom.push_back(p2);
bottom.push_back(p3);
hull = {{p0, p1, p3}, {p0, p2, p3}};
}
else
{
double distRatio = dist1 / dist2;
if (distRatio >= 2.0)
{
top.reserve(3);
top.push_back(p0);
top.push_back(p1);
top.push_back(p3);
bottom.reserve(2);
bottom.push_back(p0);
bottom.push_back(p3);
}
hull = {{p0, p1, p3}, {p0, p3}};
else if (distRatio <= 0.5)
{
top.reserve(3);
top.push_back(p0);
top.push_back(p2);
top.push_back(p3);
bottom.reserve(2);
bottom.push_back(p0);
bottom.push_back(p3);
}
hull = {{p0, p2, p3}, {p0, p3}};
else
{
top.reserve(4);
top.push_back(p0);
top.push_back(p1);
top.push_back(p2);
top.push_back(p3);
bottom.reserve(2);
bottom.push_back(p0);
bottom.push_back(p3);
}
hull = {{p0, p1, p2, p3}, {p0, p3}};
}
if (dist1 < 0.0 || dist2 < 0.0)
std::swap(top, bottom);
std::reverse(hull.begin(), hull.end());
return hull;
}
double clipConvexHullPart(const std::vector<Aggplus::PointD>& part, const bool& top,

View File

@ -934,11 +934,6 @@ int CAnnotFieldInfo::CWidgetAnnotPr::CTextWidgetPr::GetMaxLen() const { return m
const std::wstring& CAnnotFieldInfo::CWidgetAnnotPr::CTextWidgetPr::GetV() { return m_wsV; }
const std::wstring& CAnnotFieldInfo::CWidgetAnnotPr::CTextWidgetPr::GetRV() { return m_wsRV; }
const std::wstring& CAnnotFieldInfo::CWidgetAnnotPr::CTextWidgetPr::GetAPV() { return m_wsAPV; }
BYTE* CAnnotFieldInfo::CWidgetAnnotPr::CTextWidgetPr::GetRender(LONG& nLen)
{
nLen = m_nRenderLen;
return m_pRender;
}
void CAnnotFieldInfo::CWidgetAnnotPr::CTextWidgetPr::Read(NSOnlineOfficeBinToPdf::CBufferReader* pReader, int nFlags, int nWidgetFlag)
{
if (nFlags & (1 << 9))
@ -949,12 +944,6 @@ void CAnnotFieldInfo::CWidgetAnnotPr::CTextWidgetPr::Read(NSOnlineOfficeBinToPdf
m_wsRV = pReader->ReadString();
if (nFlags & (1 << 12))
m_wsAPV = pReader->ReadString();
if (nFlags & (1 << 13))
{
m_nRenderLen = pReader->ReadInt() - 4;
m_pRender = pReader->GetCurrentBuffer();
pReader->Skip(m_nRenderLen);
}
}
int CAnnotFieldInfo::CWidgetAnnotPr::CChoiceWidgetPr::GetTI() const { return m_nTI; }
@ -963,11 +952,6 @@ const std::wstring& CAnnotFieldInfo::CWidgetAnnotPr::CChoiceWidgetPr::GetAPV() {
const std::vector<int>& CAnnotFieldInfo::CWidgetAnnotPr::CChoiceWidgetPr::GetI() { return m_arrI; }
const std::vector<std::wstring>& CAnnotFieldInfo::CWidgetAnnotPr::CChoiceWidgetPr::GetArrV() { return m_arrV; }
const std::vector< std::pair<std::wstring, std::wstring> >& CAnnotFieldInfo::CWidgetAnnotPr::CChoiceWidgetPr::GetOpt() { return m_arrOpt; }
BYTE* CAnnotFieldInfo::CWidgetAnnotPr::CChoiceWidgetPr::GetRender(LONG& nLen)
{
nLen = m_nRenderLen;
return m_pRender;
}
void CAnnotFieldInfo::CWidgetAnnotPr::CChoiceWidgetPr::Read(NSOnlineOfficeBinToPdf::CBufferReader* pReader, int nFlags)
{
if (nFlags & (1 << 9))
@ -998,12 +982,6 @@ void CAnnotFieldInfo::CWidgetAnnotPr::CChoiceWidgetPr::Read(NSOnlineOfficeBinToP
for (int i = 0; i < n; ++i)
m_arrI.push_back(pReader->ReadInt());
}
if (nFlags & (1 << 15))
{
m_nRenderLen = pReader->ReadInt() - 4;
m_pRender = pReader->GetCurrentBuffer();
pReader->Skip(m_nRenderLen);
}
}
CAnnotFieldDelete::CAnnotFieldDelete() : IAdvancedCommand(AdvancedCommandType::DeleteAnnot) {}

View File

@ -86,7 +86,6 @@ public:
const std::wstring& GetV();
const std::wstring& GetRV();
const std::wstring& GetAPV();
BYTE* GetRender(LONG& nLen);
void Read(NSOnlineOfficeBinToPdf::CBufferReader* pReader, int nFlags, int nWidgetFlag);
@ -95,8 +94,6 @@ public:
std::wstring m_wsV;
std::wstring m_wsRV;
std::wstring m_wsAPV;
LONG m_nRenderLen;
BYTE* m_pRender;
};
class GRAPHICS_DECL CChoiceWidgetPr
@ -108,7 +105,6 @@ public:
const std::vector<int>& GetI();
const std::vector<std::wstring>& GetArrV();
const std::vector< std::pair<std::wstring, std::wstring> >& GetOpt();
BYTE* GetRender(LONG& nLen);
void Read(NSOnlineOfficeBinToPdf::CBufferReader* pReader, int nFlags);
@ -119,8 +115,6 @@ public:
std::vector<int> m_arrI;
std::vector<std::wstring> m_arrV;
std::vector< std::pair<std::wstring, std::wstring> > m_arrOpt;
LONG m_nRenderLen;
BYTE* m_pRender;
};
class GRAPHICS_DECL CSignatureWidgetPr

View File

@ -59,8 +59,7 @@ SOURCES += \
# alpha mask
HEADERS += \
./../AlphaMask.h \
./../AlphaMask_p.h
./../AlphaMask.h
SOURCES += \
./../AlphaMask.cpp

View File

@ -126,11 +126,6 @@ CFile.prototype["loadFromDataWithPassword"] = function(password)
return error;
};
CFile.prototype["getType"] = function()
{
return this.type;
};
CFile.prototype["close"] = function()
{
this._closeFile();

View File

@ -144,7 +144,7 @@ CFile.prototype._getInteractiveFormsInfo = function()
CFile.prototype._getAnnotationsInfo = function(pageIndex)
{
g_module_pointer.ptr = g_native_drawing_file["GetAnnotationsInfo"](pageIndex === undefined ? -1 : pageIndex);
g_module_pointer.ptr = g_native_drawing_file["GetAnnotationsInfo"](pageIndex);
return g_module_pointer;
};

View File

@ -468,20 +468,6 @@ namespace NSStructures
p1.x = static_cast<float>(p1_x);
p1.y = static_cast<float>(p1_y);
for (size_t i = 0; i < shading.patch.size(); ++i)
{
for (size_t j = 0; j < shading.patch[i].size(); ++j)
{
double patch_x = static_cast<double>(shading.patch[i][j].x);
double patch_y = static_cast<double>(shading.patch[i][j].y);
matrix.TransformPoint(patch_x, patch_y);
shading.patch[i][j].x = static_cast<float>(patch_x);
shading.patch[i][j].y = static_cast<float>(patch_y);
}
}
// sizes scale
double sqrt_det = sqrt(fabs(matrix.Determinant()));
r0 *= sqrt_det;

View File

@ -1028,8 +1028,6 @@ l_uint32 *line;
pos = (qpos + i) % 8;
npx = px + xpostab[pos];
npy = py + ypostab[pos];
if (npx < 0 || npx >= w || npy < 0 || npy >= h)
continue;
line = data + npy * wpl;
val = GET_DATA_BIT(line, npx);
if (val) {

View File

@ -3228,7 +3228,7 @@ l_int32 i, j, w, h, wplc, wplm, wpld, ncolors, index;
l_int32 rval, gval, bval, val, minval, maxval;
l_int32 *lut;
l_uint32 *datac, *datam, *datad, *linec, *linem, *lined;
PIX *pix1, *pixc, *pixm, *pixg, *pixd;
PIX *pixc, *pixm, *pixg, *pixd;
PIXCMAP *cmap, *cmapd;
PROCNAME("pixFewColorsOctcubeQuantMixed");
@ -3245,10 +3245,8 @@ PIXCMAP *cmap, *cmapd;
if (maxspan <= 2) maxspan = 15;
/* Start with a simple fixed octcube quantizer. */
if ((pix1 = pixFewColorsOctcubeQuant1(pixs, level)) == NULL)
if ((pixc = pixFewColorsOctcubeQuant1(pixs, level)) == NULL)
return (PIX *)ERROR_PTR("too many colors", procName, NULL);
pixc = pixConvertTo8(pix1, 1); /* must be 8 bpp */
pixDestroy(&pix1);
/* Identify and save color entries in the colormap. Set up a LUT
* that returns -1 for any gray pixel. */

View File

@ -45,7 +45,7 @@ namespace MetaFile
{
public:
IMetaFileBase()
: m_pOutput(NULL), m_pParent(NULL), m_pBufferData(NULL), m_bIsExternalBuffer(false), m_bError(false)
: m_pOutput(NULL), m_pBufferData(NULL), m_bIsExternalBuffer(false), m_bError(false), m_pParent(NULL)
{
m_oStream.SetStream(NULL, 0);
}

View File

@ -1113,58 +1113,4 @@ namespace MetaFile
return wsValue;
}
std::wstring ConvertToUnicode(const unsigned char* pText, unsigned long unLength, unsigned short uchCharSet)
{
NSStringExt::CConverter::ESingleByteEncoding eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_DEFAULT;;
// Соответствие Charset -> Codepage: http://support.microsoft.com/kb/165478
// http://msdn.microsoft.com/en-us/library/cc194829.aspx
// Charset Name Charset Value(hex) Codepage number
// ------------------------------------------------------
//
// DEFAULT_CHARSET 1 (x01)
// SYMBOL_CHARSET 2 (x02)
// OEM_CHARSET 255 (xFF)
// ANSI_CHARSET 0 (x00) 1252
// RUSSIAN_CHARSET 204 (xCC) 1251
// EASTEUROPE_CHARSET 238 (xEE) 1250
// GREEK_CHARSET 161 (xA1) 1253
// TURKISH_CHARSET 162 (xA2) 1254
// BALTIC_CHARSET 186 (xBA) 1257
// HEBREW_CHARSET 177 (xB1) 1255
// ARABIC _CHARSET 178 (xB2) 1256
// SHIFTJIS_CHARSET 128 (x80) 932
// HANGEUL_CHARSET 129 (x81) 949
// GB2313_CHARSET 134 (x86) 936
// CHINESEBIG5_CHARSET 136 (x88) 950
// THAI_CHARSET 222 (xDE) 874
// JOHAB_CHARSET 130 (x82) 1361
// VIETNAMESE_CHARSET 163 (xA3) 1258
switch (uchCharSet)
{
default:
case DEFAULT_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_DEFAULT; break;
case SYMBOL_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_DEFAULT; break;
case ANSI_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1252; break;
case RUSSIAN_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1251; break;
case EASTEUROPE_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1250; break;
case GREEK_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1253; break;
case TURKISH_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1254; break;
case BALTIC_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1257; break;
case HEBREW_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1255; break;
case ARABIC_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1256; break;
case SHIFTJIS_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP932; break;
case HANGEUL_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP949; break;
case 134/*GB2313_CHARSET*/: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP936; break;
case CHINESEBIG5_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP950; break;
case THAI_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP874; break;
case JOHAB_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1361; break;
case VIETNAMESE_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1258; break;
}
return NSStringExt::CConverter::GetUnicodeFromSingleByteString(pText, unLength, eCharSet);
}
}

View File

@ -47,7 +47,6 @@
namespace MetaFile
{
bool Equals(double dFirst, double dSecond, double dEpsilon = DBL_EPSILON);
std::wstring ConvertToUnicode(const unsigned char* pText, unsigned long unLength, unsigned short uchCharSet);
struct TRgbQuad
{

View File

@ -1167,29 +1167,23 @@ namespace MetaFile
arNodeAttributes.push_back({L"font-size", ConvertToWString(dFontHeight)});
NSStringUtils::CStringBuilder oFontName;
oFontName.WriteEncodeXmlString(pFont->GetFaceName());
std::wstring wsFontName = pFont->GetFaceName();
if (0 != oFontName.GetSize())
#ifndef BUILDING_WASM_MODULE
if (!wsFontName.empty())
{
#ifndef BUILDING_WASM_MODULE
NSFonts::CFontSelectFormat oFormat;
oFormat.wsName = new std::wstring(pFont->GetFaceName());
NSFonts::CFontInfo *pFontInfo = m_pParser->GetFontManager()->GetFontInfoByParams(oFormat);
if (NULL != pFontInfo && !StringEquals(*oFormat.wsName, pFontInfo->m_wsFontName))
{
oFontName.Clear();
oFontName.WriteEncodeXmlString(L"\'");
oFontName.WriteEncodeXmlString(*oFormat.wsName);
oFontName.WriteEncodeXmlString(L"\',\'");
oFontName.WriteEncodeXmlString(pFontInfo->m_wsFontName);
oFontName.WriteEncodeXmlString(L"\'");
}
#endif
arNodeAttributes.push_back({L"font-family", oFontName.GetData()});
if (NULL != pFontInfo && !StringEquals(wsFontName, pFontInfo->m_wsFontName))
wsFontName = L"&apos;" + wsFontName + L"&apos;, &apos;" + pFontInfo->m_wsFontName + L"&apos;";
}
#endif
if (!wsFontName.empty())
arNodeAttributes.push_back({L"font-family", wsFontName});
if (pFont->GetWeight() > 550)
arNodeAttributes.push_back({L"font-weight", L"bold"});
@ -1233,7 +1227,7 @@ namespace MetaFile
{L"rx", ConvertToWString((oNewRect.Right - oNewRect.Left) / 2)},
{L"ry", ConvertToWString((oNewRect.Bottom - oNewRect.Top) / 2)}};
AddStroke(arAttributes);
AddNoneFill(arAttributes);
AddFill(arAttributes);
AddTransform(arAttributes);
AddClip();

View File

@ -454,10 +454,60 @@ namespace MetaFile
return SetError();
const IFont* pFont = GetFont();
std::wstring wsText = ConvertToUnicode(oText.pOutputString, oText.unChars, (NULL != pFont) ? pFont->GetCharSet() : DEFAULT_CHARSET);
NSStringExt::CConverter::ESingleByteEncoding eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_DEFAULT;
if (pFont)
{
// Соответствие Charset -> Codepage: http://support.microsoft.com/kb/165478
// http://msdn.microsoft.com/en-us/library/cc194829.aspx
// Charset Name Charset Value(hex) Codepage number
// ------------------------------------------------------
//
// DEFAULT_CHARSET 1 (x01)
// SYMBOL_CHARSET 2 (x02)
// OEM_CHARSET 255 (xFF)
// ANSI_CHARSET 0 (x00) 1252
// RUSSIAN_CHARSET 204 (xCC) 1251
// EASTEUROPE_CHARSET 238 (xEE) 1250
// GREEK_CHARSET 161 (xA1) 1253
// TURKISH_CHARSET 162 (xA2) 1254
// BALTIC_CHARSET 186 (xBA) 1257
// HEBREW_CHARSET 177 (xB1) 1255
// ARABIC _CHARSET 178 (xB2) 1256
// SHIFTJIS_CHARSET 128 (x80) 932
// HANGEUL_CHARSET 129 (x81) 949
// GB2313_CHARSET 134 (x86) 936
// CHINESEBIG5_CHARSET 136 (x88) 950
// THAI_CHARSET 222 (xDE) 874
// JOHAB_CHARSET 130 (x82) 1361
// VIETNAMESE_CHARSET 163 (xA3) 1258
switch (pFont->GetCharSet())
{
default:
case DEFAULT_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_DEFAULT; break;
case SYMBOL_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_DEFAULT; break;
case ANSI_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1252; break;
case RUSSIAN_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1251; break;
case EASTEUROPE_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1250; break;
case GREEK_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1253; break;
case TURKISH_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1254; break;
case BALTIC_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1257; break;
case HEBREW_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1255; break;
case ARABIC_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1256; break;
case SHIFTJIS_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP932; break;
case HANGEUL_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP949; break;
case 134/*GB2313_CHARSET*/: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP936; break;
case CHINESEBIG5_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP950; break;
case THAI_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP874; break;
case JOHAB_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1361; break;
case VIETNAMESE_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1258; break;
}
}
std::wstring wsText = NSStringExt::CConverter::GetUnicodeFromSingleByteString((unsigned char*)oText.pOutputString, oText.unChars, eCharSet);
int* pDx = NULL;
if (oText.pOutputDx && oText.unChars == wsText.length())
if (oText.pOutputDx)
{
pDx = new int[oText.unChars];
if (pDx)
@ -488,7 +538,7 @@ namespace MetaFile
unsigned int unLen = 0;
int* pDx = NULL;
if (oText.pOutputDx && oText.unChars && oText.unChars == wsText.length())
if (oText.pOutputDx && oText.unChars)
{
// Здесь мы эмулируем конвертацию Utf16 в Utf32, чтобы правильно получить массив pDx
pDx = new int[oText.unChars];

View File

@ -177,8 +177,7 @@ namespace MetaFile
: m_bBanEmfProcessing(true),
m_unLogicalDpiX(96),
m_unLogicalDpiY(96),
m_dPageTransformX(1.),
m_dPageTransformY(1.)
m_dUnitKoef(1)
{
m_oHeader = oHeader;
@ -1371,19 +1370,16 @@ namespace MetaFile
UpdateOutputDC();
}
double CEmfPlusParser::GetUnitToPixel(const double& dDpi, EEmfPlusUnitType eUnitType) const
void CEmfPlusParser::UpdateMatrix(TEmfPlusXForm &oMatrix)
{
switch (eUnitType)
{
case UnitTypePixel:
case UnitTypeWorld:
case UnitTypeDisplay:
default: return 1.;
case UnitTypePoint: return dDpi / 72.;
case UnitTypeInch: return dDpi;
case UnitTypeDocument: return dDpi / 300.;
case UnitTypeMillimeter: return dDpi / 25.4;
}
const double dKoef{m_dUnitKoef * (m_unLogicalDpiX / 96)};
oMatrix.M11 *= dKoef;
oMatrix.M12 *= dKoef;
oMatrix.M21 *= dKoef;
oMatrix.M22 *= dKoef;
oMatrix.Dx *= dKoef;
oMatrix.Dy *= dKoef;
}
bool CEmfPlusParser::SaveImage(const CEmfPlusImage &oEmfPlusImage, std::wstring &wsPathToImage)
@ -1416,50 +1412,47 @@ namespace MetaFile
return true;
}
BYTE* GetClipedImage(const BYTE* pBuffer, LONG lWidth, LONG lHeight, const TRectL& oNewRect, unsigned int& nWidth, unsigned int& nHeight)
BYTE* GetClipedImage(const BYTE* pBuffer, LONG lWidth, LONG lHeight, TRectL& oNewRect)
{
if (NULL == pBuffer)
if (NULL == pBuffer ||
oNewRect.Left < 0 || oNewRect.Right < 0 ||
oNewRect.Top < 0 || oNewRect.Bottom < 0)
return NULL;
int nBeginX = (std::min)(oNewRect.Left, oNewRect.Right);
int nBeginY = (std::min)(oNewRect.Top, oNewRect.Bottom);
if (lHeight < (oNewRect.Bottom - oNewRect.Top))
oNewRect.Bottom = oNewRect.Top + lHeight;
int nEndX = (std::max)(oNewRect.Left, oNewRect.Right);
int nEndY = (std::max)(oNewRect.Top, oNewRect.Bottom);
if (lWidth < (oNewRect.Right - oNewRect.Left))
oNewRect.Right = oNewRect.Left + lWidth;
if (nBeginX >= lWidth || nEndX <= 0)
return NULL;
if (nBeginY >= lHeight || nEndY <= 0)
if (lHeight == (oNewRect.Bottom - oNewRect.Top) &&
lWidth == (oNewRect.Right - oNewRect.Left))
return NULL;
if (nBeginX <= 0 && nEndX >= lWidth &&
nBeginY <= 0 && nEndY >= lHeight)
return NULL;
int nBeginX, nBeginY, nEndX, nEndY;
if (nBeginX < 0)
nBeginX = 0;
if (nBeginY < 0)
nBeginY = 0;
nBeginX = (std::min)(oNewRect.Left, oNewRect.Right);
nBeginY = (std::min)(oNewRect.Top, oNewRect.Bottom);
if (nEndX > lWidth)
nEndX = lWidth;
if (nEndY > lHeight)
nEndY = lHeight;
nEndX = (std::max)(oNewRect.Left, oNewRect.Right);
nEndY = (std::max)(oNewRect.Top, oNewRect.Bottom);
if (nEndX <= nBeginX || nEndY <= nBeginY)
return NULL;
nWidth = nEndX - nBeginX;
nHeight = nEndY - nBeginY;
int nWidth = nEndX - nBeginX;
int nHeight = nEndY - nBeginY;
BYTE* pNewBuffer = new BYTE[nWidth * nHeight * 4];
BYTE* pCurrentLine = pNewBuffer;
int ulStride = 4 * nWidth;
for (int nPosY = nBeginY; nPosY < nEndY; ++nPosY)
ULONG ulPos = 0;
for (ULONG ulPosY = nBeginY * 4; ulPosY < nEndY * 4; ulPosY += 4)
{
memcpy(pCurrentLine, pBuffer + lWidth * 4 * nPosY + 4 * nBeginX, ulStride);
pCurrentLine += ulStride;
for (ULONG ulPosX = nBeginX * 4; ulPosX < nEndX * 4; ulPosX += 4)
{
pNewBuffer[ulPos++] = (BYTE)pBuffer[ulPosY * lWidth + ulPosX + 0];
pNewBuffer[ulPos++] = (BYTE)pBuffer[ulPosY * lWidth + ulPosX + 1];
pNewBuffer[ulPos++] = (BYTE)pBuffer[ulPosY * lWidth + ulPosX + 2];
pNewBuffer[ulPos++] = (BYTE)pBuffer[ulPosY * lWidth + ulPosX + 3];
}
}
return pNewBuffer;
@ -1470,17 +1463,28 @@ namespace MetaFile
if (NULL == pImageBuffer || lWidth == 0 || lHeight == 0)
return S_FALSE;
BYTE* pTempLine = (BYTE*)malloc(lWidth * 4);
const ULONG ulStride = 4 * lWidth;
BYTE oBuffer[4] = {0, 0, 0, 0};
for (UINT nPosY = 0; nPosY < lHeight / 2; ++nPosY)
for (ULONG ulPosY = 0; ulPosY < lHeight / 2 * 4; ulPosY += 4)
{
memcpy(pTempLine, pImageBuffer + nPosY * ulStride, ulStride);
memcpy(pImageBuffer + nPosY * ulStride, pImageBuffer + (lHeight - nPosY - 1) * ulStride, ulStride);
memcpy(pImageBuffer + (lHeight - nPosY - 1) * ulStride, pTempLine, ulStride);
}
for (ULONG ulPosX = 0; ulPosX < lWidth * 4; ulPosX += 4)
{
oBuffer[0] = pImageBuffer[ulPosY * lWidth + ulPosX + 0];
oBuffer[1] = pImageBuffer[ulPosY * lWidth + ulPosX + 1];
oBuffer[2] = pImageBuffer[ulPosY * lWidth + ulPosX + 2];
oBuffer[3] = pImageBuffer[ulPosY * lWidth + ulPosX + 3];
free(pTempLine);
pImageBuffer[ulPosY * lWidth + ulPosX + 0] = pImageBuffer[((lHeight - 1) * 4 - ulPosY) * lWidth + ulPosX + 0];
pImageBuffer[ulPosY * lWidth + ulPosX + 1] = pImageBuffer[((lHeight - 1) * 4 - ulPosY) * lWidth + ulPosX + 1];
pImageBuffer[ulPosY * lWidth + ulPosX + 2] = pImageBuffer[((lHeight - 1) * 4 - ulPosY) * lWidth + ulPosX + 2];
pImageBuffer[ulPosY * lWidth + ulPosX + 3] = pImageBuffer[((lHeight - 1) * 4 - ulPosY) * lWidth + ulPosX + 3];
pImageBuffer[((lHeight - 1) * 4 - ulPosY) * lWidth + ulPosX + 0] = oBuffer[0];
pImageBuffer[((lHeight - 1) * 4 - ulPosY) * lWidth + ulPosX + 1] = oBuffer[1];
pImageBuffer[((lHeight - 1) * 4 - ulPosY) * lWidth + ulPosX + 2] = oBuffer[2];
pImageBuffer[((lHeight - 1) * 4 - ulPosY) * lWidth + ulPosX + 3] = oBuffer[3];
}
}
return S_OK;
}
@ -1629,17 +1633,18 @@ namespace MetaFile
TRectL oClipRect;
oClipRect.Left = std::floor((oSrcRect.dX - oFileBounds.Left) * dScale);
oClipRect.Top = std::floor((oSrcRect.dY - oFileBounds.Top) * dScale);
oClipRect.Right = std::floor((oSrcRect.dX + oSrcRect.dWidth - oFileBounds.Left) * dScale);
oClipRect.Bottom = std::floor((oSrcRect.dY + oSrcRect.dHeight - oFileBounds.Top) * dScale);
oClipRect.Left = oSrcRect.dX * dScale;
oClipRect.Top = oSrcRect.dY * dScale;
oClipRect.Right = (oSrcRect.dX + oSrcRect.dWidth) * dScale;
oClipRect.Bottom = (oSrcRect.dY + oSrcRect.dHeight) * dScale;
unsigned int nW = (unsigned int)nWidth;
unsigned int nH = (unsigned int)nHeight;
BYTE* pNewBuffer = GetClipedImage(pPixels, nWidth, nHeight, oClipRect, nW, nH);
BYTE* pNewBuffer = GetClipedImage(pPixels, nWidth, nHeight, oClipRect);
const unsigned int unWidth = std::min(((unsigned int)abs(oClipRect.Right - oClipRect.Left)), ((unsigned int)nWidth ));
const unsigned int unHeight = std::min(((unsigned int)abs(oClipRect.Bottom - oClipRect.Top)), ((unsigned int)nHeight));
m_pInterpretator->DrawBitmap(arPoints[0].X, arPoints[0].Y, arPoints[1].X - arPoints[0].X - m_pDC->GetPixelWidth(), arPoints[2].Y - arPoints[0].Y - m_pDC->GetPixelHeight(),
(NULL != pNewBuffer) ? pNewBuffer : pPixels, nW, nH);
(NULL != pNewBuffer) ? pNewBuffer : pPixels, unWidth, unHeight);
RELEASEINTERFACE(pGrRenderer);
RELEASEARRAYOBJECTS(pNewBuffer);
@ -1708,17 +1713,15 @@ namespace MetaFile
TRectL oClipRect;
oClipRect.Left = std::floor(oSrcRect.dX);
oClipRect.Top = std::floor(oSrcRect.dY);
oClipRect.Right = std::floor((oSrcRect.dX + oSrcRect.dWidth));
oClipRect.Bottom = std::floor((oSrcRect.dY + oSrcRect.dHeight));
oClipRect.Left = oSrcRect.dX;
oClipRect.Top = oSrcRect.dY;
oClipRect.Right = (oSrcRect.dX + oSrcRect.dWidth);
oClipRect.Bottom = (oSrcRect.dY + oSrcRect.dHeight);
unsigned int nW = (unsigned int)unWidth;
unsigned int nH = (unsigned int)unHeight;
BYTE* pNewBuffer = GetClipedImage(pBytes, unWidth, unHeight, oClipRect, nW, nH);
BYTE* pNewBuffer = GetClipedImage(pBytes, unWidth, unHeight, oClipRect);
m_pInterpretator->DrawBitmap(arPoints[0].X, arPoints[0].Y, arPoints[1].X - arPoints[0].X, arPoints[2].Y - arPoints[0].Y,
(NULL != pNewBuffer) ? pNewBuffer : pBytes, nW, nH);
(NULL != pNewBuffer) ? pNewBuffer : pBytes, fabs(oClipRect.Right - oClipRect.Left), fabs(oClipRect.Bottom - oClipRect.Top));
if (!bExternalBuffer)
RELEASEARRAYOBJECTS(pBytes);
@ -3176,16 +3179,24 @@ namespace MetaFile
m_bBanEmfProcessing = true;
short shPageUnit = ExpressValue(unShFlags, 0, 7);
double dUnitKoef;
m_oStream >> dUnitKoef;
m_oStream >> m_dUnitKoef;
m_dPageTransformX = dUnitKoef * GetUnitToPixel(m_unLogicalDpiX, static_cast<EEmfPlusUnitType>(shPageUnit));
m_dPageTransformY = dUnitKoef * GetUnitToPixel(m_unLogicalDpiY, static_cast<EEmfPlusUnitType>(shPageUnit));
switch (shPageUnit)
{
case UnitTypePixel:
case UnitTypeWorld:
case UnitTypeDisplay:
default: break;
case UnitTypePoint: m_dUnitKoef *= m_unLogicalDpiX * 72.f; break;
case UnitTypeInch: m_dUnitKoef *= m_unLogicalDpiX; break;
case UnitTypeDocument: m_dUnitKoef *= m_unLogicalDpiX / 300.f; break;
case UnitTypeMillimeter: m_dUnitKoef *= m_unLogicalDpiX / 25.4f; break;
}
TEmfPlusXForm oUnitKoefMatrix(m_dPageTransformX, 0, 0, m_dPageTransformY, 0, 0);
m_pDC->MultiplyTransform(oUnitKoefMatrix, MWT_LEFTMULTIPLY);
TXForm oMatrix(m_dUnitKoef, 0, 0, m_dUnitKoef, 0, 0);
m_pDC->MultiplyTransform(oMatrix, MWT_LEFTMULTIPLY);
UpdateOutputDC();
}
@ -3196,10 +3207,6 @@ namespace MetaFile
m_oStream >> oMatrix;
m_pDC->MultiplyTransform(oMatrix, MWT_SET);
TEmfPlusXForm oUnitKoefMatrix(m_dPageTransformX, 0, 0, m_dPageTransformY, 0, 0);
m_pDC->MultiplyTransform(oUnitKoefMatrix, MWT_LEFTMULTIPLY);
UpdateOutputDC();
}

View File

@ -87,7 +87,7 @@ namespace MetaFile
template<typename T> std::vector<TEmfPlusPointF> GetConvertedPoints(std::vector<T>arPoints);
template<typename T> TEmfPlusRectF GetConvertedRectangle(T oRectangle);
double GetUnitToPixel(const double& dDpi, EEmfPlusUnitType eUnitType) const;
void UpdateMatrix(TEmfPlusXForm& oMatrix);
bool SaveImage(const CEmfPlusImage& oImage, std::wstring& wsPathToImage);
@ -176,8 +176,7 @@ namespace MetaFile
unsigned int m_unLogicalDpiX;
unsigned int m_unLogicalDpiY;
double m_dPageTransformX;
double m_dPageTransformY;
double m_dUnitKoef;
typedef std::map<unsigned int, CEmfPlusObject*> EmfPlusObjects;

View File

@ -469,8 +469,8 @@ namespace MetaFile
// Обновляем обратную матрицу
TEmfXForm* pT = &m_oTransform;
const double dDet = pT->M11 * pT->M22 - pT->M12 * pT->M21;
if (Equals(0., dDet, 0.0001))
double dDet = pT->M11 * pT->M22 - pT->M12 * pT->M21;
if (dDet < 0.0001 && dDet > 0.0001)
{
m_oInverseTransform.M11 = 1;
m_oInverseTransform.M12 = 0;
@ -479,15 +479,13 @@ namespace MetaFile
m_oInverseTransform.Dx = 0;
m_oInverseTransform.Dy = 0;
}
else
{
m_oInverseTransform.M11 = pT->M22 / dDet;
m_oInverseTransform.M12 = -pT->M12 / dDet;
m_oInverseTransform.M21 = -pT->M21 / dDet;
m_oInverseTransform.M22 = pT->M22 / dDet;
m_oInverseTransform.Dx = pT->Dy * pT->M21 / dDet - pT->Dx * pT->M22 / dDet;
m_oInverseTransform.Dy = pT->Dx * pT->M12 / dDet - pT->Dy * pT->M11 / dDet;
}
m_oInverseTransform.M11 = pT->M22 / dDet;
m_oInverseTransform.M12 = -pT->M12 / dDet;
m_oInverseTransform.M21 = -pT->M21 / dDet;
m_oInverseTransform.M22 = pT->M22 / dDet;
m_oInverseTransform.Dx = pT->Dy * pT->M21 / dDet - pT->Dx * pT->M22 / dDet;
m_oInverseTransform.Dy = pT->Dx * pT->M12 / dDet - pT->Dy * pT->M11 / dDet;
UpdateFinalTransform();
}
@ -716,21 +714,21 @@ namespace MetaFile
const TEmfWindow& oWindow{GetWindow()};
const TEmfWindow& oViewPort{GetViewport()};
double dM11 = ((oViewPort.ulW >= 0) ? 1. : -1.) * GetPixelWidth();
double dM22 = ((oViewPort.ulH >= 0) ? 1. : -1.) * GetPixelHeight();
double dM11 = (oViewPort.ulW >= 0) ? 1 : -1;
double dM22 = (oViewPort.ulH >= 0) ? 1 : -1;
TEmfXForm oWindowXForm(1, 0, 0, 1, -(oWindow.lX * dM11), -(oWindow.lY * dM22));
TEmfXForm oViewportXForm(dM11, 0, 0, dM22, oViewPort.lX, oViewPort.lY);
TEmfXForm oWindowXForm(1, 0, 0, 1, -(oWindow.lX * GetPixelWidth() * dM11), -(oWindow.lY * GetPixelHeight() * dM22));
TEmfXForm oViewportXForm(GetPixelWidth() * dM11, 0, 0, GetPixelHeight() * dM22, oViewPort.lX, oViewPort.lY);
m_oFinalTransform.Init();
m_oFinalTransform.Multiply(oWindowXForm, MWT_RIGHTMULTIPLY);
m_oFinalTransform.Multiply(m_oTransform, MWT_RIGHTMULTIPLY);
m_oFinalTransform.Multiply(oViewportXForm, MWT_RIGHTMULTIPLY);
m_oFinalTransform.Multiply(oWindowXForm, MWT_RIGHTMULTIPLY);
m_oFinalTransform2.Init();
m_oFinalTransform2.Multiply(oWindowXForm, MWT_RIGHTMULTIPLY);
m_oFinalTransform2.Multiply(m_oTransform, MWT_RIGHTMULTIPLY);
m_oFinalTransform2.Multiply(oViewportXForm, MWT_RIGHTMULTIPLY);
m_oFinalTransform2.Multiply(oWindowXForm, MWT_RIGHTMULTIPLY);
}
void CEmfDC::FixIsotropic()

View File

@ -149,13 +149,63 @@ namespace MetaFile
if (NULL != m_pParser)
pFont = m_pParser->GetFont();
const std::wstring wsText{ConvertToUnicode(pString, (long)shStringLength, (NULL != pFont) ? pFont->GetCharSet() : DEFAULT_CHARSET)};
NSStringExt::CConverter::ESingleByteEncoding eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_DEFAULT;;
if (pFont)
{
// Соответствие Charset -> Codepage: http://support.microsoft.com/kb/165478
// http://msdn.microsoft.com/en-us/library/cc194829.aspx
// Charset Name Charset Value(hex) Codepage number
// ------------------------------------------------------
//
// DEFAULT_CHARSET 1 (x01)
// SYMBOL_CHARSET 2 (x02)
// OEM_CHARSET 255 (xFF)
// ANSI_CHARSET 0 (x00) 1252
// RUSSIAN_CHARSET 204 (xCC) 1251
// EASTEUROPE_CHARSET 238 (xEE) 1250
// GREEK_CHARSET 161 (xA1) 1253
// TURKISH_CHARSET 162 (xA2) 1254
// BALTIC_CHARSET 186 (xBA) 1257
// HEBREW_CHARSET 177 (xB1) 1255
// ARABIC _CHARSET 178 (xB2) 1256
// SHIFTJIS_CHARSET 128 (x80) 932
// HANGEUL_CHARSET 129 (x81) 949
// GB2313_CHARSET 134 (x86) 936
// CHINESEBIG5_CHARSET 136 (x88) 950
// THAI_CHARSET 222 (xDE) 874
// JOHAB_CHARSET 130 (x82) 1361
// VIETNAMESE_CHARSET 163 (xA3) 1258
switch (pFont->GetCharSet())
{
default:
case DEFAULT_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_DEFAULT; break;
case SYMBOL_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_DEFAULT; break;
case ANSI_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1252; break;
case RUSSIAN_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1251; break;
case EASTEUROPE_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1250; break;
case GREEK_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1253; break;
case TURKISH_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1254; break;
case BALTIC_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1257; break;
case HEBREW_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1255; break;
case ARABIC_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1256; break;
case SHIFTJIS_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP932; break;
case HANGEUL_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP949; break;
case 134/*GB2313_CHARSET*/: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP936; break;
case CHINESEBIG5_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP950; break;
case THAI_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP874; break;
case JOHAB_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1361; break;
case VIETNAMESE_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1258; break;
}
}
std::wstring wsText = NSStringExt::CConverter::GetUnicodeFromSingleByteString((const unsigned char*)pString, (long)shStringLength, eCharSet);
TPointD oScale((m_pParser->IsWindowFlippedX()) ? -1 : 1, (m_pParser->IsWindowFlippedY()) ? -1 : 1);
std::vector<double> arDx(0);
if (NULL != pDx && shStringLength == wsText.length())
if (NULL != pDx)
arDx = std::vector<double>(pDx, pDx + wsText.length());
WriteText(wsText, TPointD(shX, shY), oRectangle, oScale, arDx);

View File

@ -182,8 +182,7 @@ namespace MetaFile
std::wstring CWmfFont::GetFaceName() const
{
const std::wstring wsFontName(ConvertToUnicode((const unsigned char*)uchFacename, 32, uchCharSet));
return wsFontName.substr(0, wsFontName.find(L'\0'));
return std::wstring(NSStringExt::CConverter::GetUnicodeFromSingleByteString((const unsigned char*)uchFacename, 32).c_str());
}
int CWmfFont::GetWeight() const

View File

@ -52,7 +52,7 @@ namespace MetaFile
m_oStream.SetCurrentBlockSize(m_unRecordSize);
if (NULL != m_pInterpretator)
PRINT_WMF_RECORD(ushType);
PRINT_WMF_RECORD(ushType)
switch (ushType)
{

View File

@ -353,7 +353,57 @@ namespace MetaFile
}
const IFont* pFont = GetFont();
std::wstring wsText = ConvertToUnicode(pString, (long)unCharsCount, (NULL != pFont) ? pFont->GetCharSet() : DEFAULT_CHARSET);
NSStringExt::CConverter::ESingleByteEncoding eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_DEFAULT;;
if (pFont)
{
// Соответствие Charset -> Codepage: http://support.microsoft.com/kb/165478
// http://msdn.microsoft.com/en-us/library/cc194829.aspx
// Charset Name Charset Value(hex) Codepage number
// ------------------------------------------------------
//
// DEFAULT_CHARSET 1 (x01)
// SYMBOL_CHARSET 2 (x02)
// OEM_CHARSET 255 (xFF)
// ANSI_CHARSET 0 (x00) 1252
// RUSSIAN_CHARSET 204 (xCC) 1251
// EASTEUROPE_CHARSET 238 (xEE) 1250
// GREEK_CHARSET 161 (xA1) 1253
// TURKISH_CHARSET 162 (xA2) 1254
// BALTIC_CHARSET 186 (xBA) 1257
// HEBREW_CHARSET 177 (xB1) 1255
// ARABIC _CHARSET 178 (xB2) 1256
// SHIFTJIS_CHARSET 128 (x80) 932
// HANGEUL_CHARSET 129 (x81) 949
// GB2313_CHARSET 134 (x86) 936
// CHINESEBIG5_CHARSET 136 (x88) 950
// THAI_CHARSET 222 (xDE) 874
// JOHAB_CHARSET 130 (x82) 1361
// VIETNAMESE_CHARSET 163 (xA3) 1258
switch (pFont->GetCharSet())
{
default:
case DEFAULT_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_DEFAULT; break;
case SYMBOL_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_DEFAULT; break;
case ANSI_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1252; break;
case RUSSIAN_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1251; break;
case EASTEUROPE_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1250; break;
case GREEK_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1253; break;
case TURKISH_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1254; break;
case BALTIC_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1257; break;
case HEBREW_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1255; break;
case ARABIC_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1256; break;
case SHIFTJIS_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP932; break;
case HANGEUL_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP949; break;
case 134/*GB2313_CHARSET*/: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP936; break;
case CHINESEBIG5_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP950; break;
case THAI_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP874; break;
case JOHAB_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1361; break;
case VIETNAMESE_CHARSET: eCharSet = NSStringExt::CConverter::ESingleByteEncoding::SINGLE_BYTE_ENCODING_CP1258; break;
}
}
std::wstring wsText = NSStringExt::CConverter::GetUnicodeFromSingleByteString((const unsigned char*)pString, (long)unCharsCount, eCharSet);
if (NULL != m_pInterpretator)
{
@ -361,7 +411,7 @@ namespace MetaFile
TranslatePoint(nX, nY, dX, dY);
double* pdDx = NULL;
if (NULL != pDx && unCharsCount == wsText.length())
if (NULL != pDx)
{
pdDx = new double[unCharsCount];
if (pdDx)

View File

@ -11,8 +11,8 @@
#undef DrawText
#endif
#define PRINT_WMF_RECORD(type) do {} while(false)
#define PRINT_WMF_LOG(text) do {} while(false)
#define PRINT_WMF_RECORD(type) do {} while(false);
#define PRINT_WMF_LOG(text) do {} while(false);
#ifdef _DEBUG
#define LOG_WMF_RECORDS 1
@ -105,13 +105,13 @@
};
#define PRINT_WMF_RECORD(type) \
do {\
{\
std::map<UINT, std::string>::const_iterator itFound = mWmfRecords.find(type); \
if (mWmfRecords.cend() != itFound) \
std::cout << itFound->second << std::endl; \
else \
std::cout << "Unknown record: " << type << std::endl; \
} while(false)
}
#endif
#endif
#endif

View File

@ -571,20 +571,20 @@ namespace MetaFile
const TWmfWindow& oWindow{GetWindow()};
const TWmfWindow& oViewPort{GetViewport()};
double dM11 = ((oViewPort.w >= 0) ? 1. : -1.) * GetPixelWidth();
double dM22 = ((oViewPort.h >= 0) ? 1. : -1.) * GetPixelHeight();
double dM11 = (oViewPort.w >= 0) ? 1 : -1;
double dM22 = (oViewPort.h >= 0) ? 1 : -1;
TEmfXForm oWindowXForm(1, 0, 0, 1, -(oWindow.x * dM11), -(oWindow.y * dM22));
TEmfXForm oViewportXForm(dM11, 0, 0, dM22, oViewPort.x, oViewPort.y);
TEmfXForm oWindowXForm(1, 0, 0, 1, -(oWindow.x * GetPixelWidth() * dM11), -(oWindow.y * GetPixelHeight() * dM22));
TEmfXForm oViewportXForm(GetPixelWidth() * dM11, 0, 0, GetPixelHeight() * dM22, oViewPort.x, oViewPort.y);
m_oFinalTransform.Init();
m_oFinalTransform.Multiply(m_oTransform, MWT_RIGHTMULTIPLY);
m_oFinalTransform.Multiply(oViewportXForm, MWT_RIGHTMULTIPLY);
m_oFinalTransform.Multiply(m_oTransform, MWT_RIGHTMULTIPLY);
m_oFinalTransform.Multiply(oWindowXForm, MWT_RIGHTMULTIPLY);
m_oFinalTransform2.Init();
m_oFinalTransform2.Multiply(m_oTransform, MWT_RIGHTMULTIPLY);
m_oFinalTransform2.Multiply(oViewportXForm, MWT_RIGHTMULTIPLY);
// m_oFinalTransform2.Multiply(m_oTransform, MWT_RIGHTMULTIPLY);
m_oFinalTransform2.Multiply(oWindowXForm, MWT_RIGHTMULTIPLY);
}

View File

@ -1,7 +1,8 @@
#include "CSvgParser.h"
#include <algorithm>
#include <cctype>
#include "SvgUtils.h"
#include <iostream>
#include "CSvgFile.h"
@ -40,70 +41,17 @@ namespace SVG
m_pFontManager = pFontManager;
}
std::string FindEncoding(const std::string& wsContent)
{
size_t unEncodingBegin = wsContent.find("encoding");
if (std::string::npos == unEncodingBegin)
return std::string();
unEncodingBegin += 8;
while (unEncodingBegin < wsContent.length() && std::isspace(wsContent[unEncodingBegin]))
++unEncodingBegin;
if (unEncodingBegin >= wsContent.length() || '=' != wsContent[unEncodingBegin++])
return std::string();
while (unEncodingBegin < wsContent.length() && std::isspace(wsContent[unEncodingBegin]))
++unEncodingBegin;
if (unEncodingBegin >= wsContent.length() || ('\'' != wsContent[unEncodingBegin] && '"' != wsContent[unEncodingBegin]))
return std::string();
std::string::const_iterator itEncodingValueBegin = std::find_if(wsContent.cbegin() + unEncodingBegin + 1, wsContent.cend(), [](char chElement){ return !isspace(chElement);});
if (wsContent.cend() == itEncodingValueBegin)
return std::string();
std::string::const_iterator itEncodingValueEnd = std::find_if(itEncodingValueBegin, wsContent.cend(), [](char chElement){ return isspace(chElement) || '\'' == chElement || '\"' == chElement;});
if (wsContent.cend() == itEncodingValueEnd)
return std::string();
return std::string(itEncodingValueBegin, itEncodingValueEnd);
}
bool CSvgParser::LoadFromFile(const std::wstring &wsFile, CGraphicsContainer* pContainer, CSvgFile* pFile) const
{
if (wsFile.empty() || NULL == pFile)
return false;
std::string sXml;
if (!NSFile::CFileBinary::ReadAllTextUtf8A(wsFile, sXml))
return false;
size_t unFoundBegin = sXml.find("<svg");
NSUnicodeConverter::CUnicodeConverter oConverter;
std::wstring wsContent;
if (std::string::npos != unFoundBegin)
{
std::string sEncoding = FindEncoding(sXml.substr(0, unFoundBegin));
std::transform(sEncoding.begin(), sEncoding.end(), sEncoding.begin(), tolower);
sXml.erase(0, unFoundBegin);
if (!sEncoding.empty() && "utf-8" != sEncoding)
wsContent = oConverter.toUnicode(sXml, sEncoding.c_str());
else
wsContent = UTF8_TO_U(sXml);
}
else
std::wstring wsXml;
if (!NSFile::CFileBinary::ReadAllTextUtf8(wsFile, wsXml))
return false;
XmlUtils::IXmlDOMDocument::DisableOutput();
bool bResult = LoadFromString(wsContent, pContainer, pFile);
bool bResult = LoadFromString(wsXml, pContainer, pFile);
XmlUtils::IXmlDOMDocument::EnableOutput();
return bResult;

Some files were not shown because too many files have changed in this diff Show More